Dynamic Class Loading using Java Reflection API

java-reflection-api-dynamic-class-loadingOne 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.
Get our Articles via Email. Enter your email address.

You may also like...

32 Comments

  1. Madhukar says:

    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.

  2. sandeep says:

    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……

  3. madan says:

    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.

      String returnValue = (String) myMethod.invoke(whatInstance,
                          new Object[] { methodParameter1, methodParameter2, methodParameter3 });
       

      • regy George says:

        thank you so much.

  4. Amira says:

    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.

  5. Amina says:

    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?

    • Sumit says:

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

  6. Himanil says:

    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

  7. Joseph Kingston Leo says:

    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 ????.

    • Sumit says:

      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

    • Sumit Vadaviya says:

      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

  8. Rakesh Chandra says:

    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?

  9. SK says:

    Thanks Viral, You are doing great job, your site is so helpful…

  10. JKG says:

    Can someone explain me this line??

    String classNameToBeLoaded = “net.viralpatel.itext.pdf.DemoClass”

    I need to know hwats the package in my project

  11. NKP says:

    Thanks Viral. This site is really helpful to me

  12. sumit says:

    hey viralpatel can u tell me how to excute the above code……..urgent

  13. Shivani says:

    Thanks Viral. This page is also good for understanding Java reflection

    http://www.programmerinterview.com/index.php/java-questions/java-reflection-example/

  14. Deepesh says:

    Hey JKG,

    net.viralpatel.itext.pdf.DemoClass has DemoClass as java class name and rest of the things before is a package name. You can give any name in package like –

    test.DemoClass but the good way is which is given above..

  15. Tosha says:

    hey viral, could you plz let me know how to use this code for an constructor instead of a method??
    thanx

  16. sina says:

    Hi
    What is the difference when we create an object of the base class and call its method?
    why we should do reflection here ?

  17. prashant desai says:

    thank you for this code of example it is great to me ?

  18. Mike Goshorn says:

    So what if the class was not in the classpath when the VM started. What if I wanted to add the class to the classpath, then load the class afterwards. Doesn’t the Browser do something like that when loading Applets?

  19. Saeed NB says:

    hi, thanks for your usefull example, but I have a problem, when I edit .java file and save it, in runtime when I reload it, it doesn’t change? Can you help me please?

  20. Saeed NB says:

    how can I reload a class ?

  21. Indira Choudahry says:

    What a simple and useful way to explain..
    Thanks a lot for this information

  22. Sai Kumar says:

    Hi ViralPatel,

    How about to call all the mandatory methods in a class.
    It is very difficult to write right with reflection.

    Regards,
    Sai

  23. rana says:

    Object whatInstance = myClass.newInstance();
    with that instance i can directly call method of that class .I want to understand then what is the significance of invoking method using above code .?

  24. David says:

    If I want to load a class passing a own class, if I do it:
    Method method = tempClass.getMethod(“printData”,person.core.getClass());

    If the method to invoke is
    public void printData(Person person){
    System.out.println(person.getName())
    }

    I recived a java.lang.NoSuchMethodException

  25. David says:

    Sorry, there are a mistake in the upper example. I write my real case:

    The loader:
    ICore core = new ICore();
    urlClassLoader = new URLClassLoader(new URL[]{new URL(“file:///”+f.getAbsolutePath())});
    Class tempClass = urlClassLoader.loadClass(modulePackage);
    Constructor constructor = tempClass.getConstructor();
    Object tmpConstructor = constructor.newInstance();

    Method method = tempClass.getMethod(methodName,new Class[]{String.class,ICore.class});
    return (ArrayList ) method.invoke(tmpConstructor,info,core);

    The ICore class:
    public class ICore {

    private String name;

    public ICore(){
    this.name = “david”;
    }
    }

    the target method:
    public class Controller {

    public ArrayList getData(String input,ICore core){
    ArrayList list = new ArrayList();

    System.out.println(core.getName());
    }
    }

    If I do this I have next error:
    java.lang.NoSuchMethodException: Controller.getData(ICore)

    What is happening? how can I do it?

  26. Kale-ab says:

    Can this work without compiling the .java into a .class file?

Leave a Reply

Your email address will not be published. Required fields are marked *