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. Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
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]
thank you so much.
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?
Thanks Viral, You are doing great job, your site is so helpful...
Can someone explain me this line??
String classNameToBeLoaded = "net.viralpatel.itext.pdf.DemoClass"
I need to know hwats the package in my project