Dynamic Class Loading using Java Reflection API

http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/

package net.viralpatel.itext.pdf;

public class DemoClass {

public String demoMethod(String demoParam) {System.

out.println("Parameter passed: " + demoParam);

return DemoClass.class.getName();

}

}

package net.viralpatel.itext.pdf;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.*;

 

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";

// Validation of instance

System.err.println("what instance of Demo: " + (whatInstance instanceof DemoClass) );

System.err.println("what instance of Ext: " + (whatInstance instanceof ExtClass) );System.

err.println("what instance of Stg: " + (whatInstance instanceof String) );

ExtClass ext = (ExtClass) whatInstance;

System.
err.println("ext instance of Ext: " + (ext instanceof ExtClass) );

System.err.println("ext instance of Demo: " + (ext instanceof DemoClass) );

// 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 });

// all done

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();

}

}

}