Dynamic Class Loading using Java Reflection API

One of the reason why Java language has been so useful and used widely is the set of APIs that comes with the language (and 3rd party APIs like iText etc). Using these APIs one do a whole lot unimaginable stuff. Java Reflection API are one of such APIs that extend the horizon of a Java programmer and enables him to code some really great stuffs. Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible. Dynamic Java Class loading is an important feature of the Java Virtual Machine because it provides the Java platform with the ability to install software components at run-time. It has a number of unique characteristics. First of all, lazy loading means that classes are loaded on demand and at the last moment possible. Second, dynamic class loading maintains the type safety of the Java Virtual Machine by adding link-time checks, which replace certain run-time checks and are performed only once. Moreover, programmers can define their own class loaders that, for example, specify the remote location from which certain classes are loaded, or assign appropriate security attributes to them. Finally, class loaders can be used to provide separate name spaces for various software components. For example, a browser can load applets from different web pages using separate class loaders, thus maintaining a degree of isolation between those applet classes. In fact, these applets can contain classes of the same name — these classes are treated as distinct types by the Java Virtual Machine. Let us see an example of Dynamic class loading using Java Reflection API. Following is our DemoClass that needs to be loaded dynamically and method demoMethod() needs to be called.
class DemoClass { public String demoMethod(String demoParam) { System.out.println("Parameter passed: " + demoParam); return DemoClass.class.getName(); } }
Code language: Java (java)
So to load above class file dynamically following code can be used.
public class DynamicClassLoadingExample { public static void main(String[] args) { try { ClassLoader myClassLoader = ClassLoader.getSystemClassLoader(); // Step 2: Define a class to be loaded. String classNameToBeLoaded = "net.viralpatel.itext.pdf.DemoClass"; // Step 3: Load the class Class myClass = myClassLoader.loadClass(classNameToBeLoaded); // Step 4: create a new instance of that class Object whatInstance = myClass.newInstance(); String methodParameter = "a quick brown fox"; // Step 5: get the method, with proper parameter signature. // The second parameter is the parameter type. // There can be multiple parameters for the method we are trying to call, // hence the use of array. Method myMethod = myClass.getMethod("demoMethod", new Class[] { String.class }); // Step 6: // Calling the real method. Passing methodParameter as // parameter. You can pass multiple parameters based on // the signature of the method you are calling. Hence // there is an array. String returnValue = (String) myMethod.invoke(whatInstance, new Object[] { methodParameter }); System.out.println("The value returned from the method is:" + returnValue); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
Code language: Java (java)
The above code is pretty much self explanatory. We have used ClassLoader.getSystemClassLoader() method to get instance of class java.lang.ClassLoader. We have loaded our demo class DemoClass using method loadClass() of ClassLoader and invoked the desired method.

View Comments

  • Sweet quick refresher of using Java Reflection. I love the ability to read private methods and invoke them using Java reflection.
    Java reflection can help us load only certain required classes by taking the decision at run time instead of loading bunch of classes during compile time.

  • very good explanation of java run time environment this is really gud article for those people who started a carrier in java for initial information......

  • very good example, and if my method has more than one parameter then what are the changes should be done in the above code

    • @Madan - If your method has more than one parameter than you can pass it while calling invoke() method like below.
      [code gutter="false" language="java"]
      String returnValue = (String) myMethod.invoke(whatInstance,
      new Object[] { methodParameter1, methodParameter2, methodParameter3 });
      [/code]

  • Plllz can any one help me i want load a class but i have only fille.class ,,,i haven't .java file how can i make it ???

    • @Amira: You can load .class file dynamically by just placing .class file in your project's (JVM's) classpath and calling Clasloader.loadClass() method as specified in above example.

  • So when we have multiple classes, multiple methods to be loaded, we would need the loader to be aware of classname , method1name(params..) etc for each class/method right?
    Also you say you can place the .class file in your projects classpath - How is this done exactly?

    • your .class which have class name, method name with all the required parameters pre-available in order to load the .class file.

  • Hey!!
    I am getting NoClassDefFoundError while executing the above code block.
    Here is an stake trace:
    Exception in thread "main" java.lang.NoClassDefFoundError: net/viralpatel/itext
    pdf/DemoClass (wrong name: DemoClass)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at DynamicClassLoadingExample.main(DynamicClassLoadingExample.java:16)
    -----
    can you help me to sort it out....
    thanks

  • Hi I have doubt u told this one as dynamically loading classes.my doubt is when class loader is running as a program , already loaded class is got changed now class loader will pick the latest changed one ????.

    • No. Newly updated class won't be reflected. Container will retain old version class in memory. To load newly updated class. you must start your server

    • Sorry for above comment. I improve that.
      No. Newly updated class won’t be reflected. Container will retain old version class in memory. To load newly updated class. you must restart your server

  • Hi,

    This is a very nice example to learn dynamic class loading very quickly.
    Here the class being loaded have default constructor. But what if we have to load a class which don't have default constructor? Is there any way to load that also?

  • Can someone explain me this line??

    String classNameToBeLoaded = "net.viralpatel.itext.pdf.DemoClass"

    I need to know hwats the package in my project

Share
Published by
Viral Patel
Tags: dynamic class Java java class loading java reflection api reflection api

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago