Lets try and put this in perspective. for some or other reason, you or your has this dire need to hot swop classes in your Java EE solution, maybe because of some trivial reason, or maybe because you are a freaking genius and have this magic trick up your sleeve, either way you have to get it done.
Lets start with a simple example:
First, we get the foundation in place.
N.B The jar file needs to be included in the classpath
MyPlugandPlayEngin.java
public interface MyPnPInterface{
// This interface only makes life easier when defining the scope and functionality of the dynamic class
String doStuff(Properties properties);
}
public class MyPlugandPlayEngin{
public static main(String[] args){
//If you want you can use a custom classloader here, else just use the default, supplied by the VM
URLClassLoader classLoader = null;
if (this.driverFilePaths != null){
classLoader = new URLClassLoader();
}
MyPnPInterface pnp = null;
try {
if (classLoader != null){
// Class.forName will return a Class object, so you can then just return instance and cast to the interface
pnp = (MyPnPInterface ) Class.forName(args[0], true, classLoader).newInstance();
DriverManager.registerDriver(driver);
classLoader.loadClass(this.className);
}else{
// Default classloader
Class clazz = Class.forName(args[0]);
pnp = (MyPnPInterface ) clazz.newInstance();
}
Properties properties = new Properties();
properties.setProperty("property1", args[1]);
pnp.doStuff(properties);
}catch Exception e(){
e.printStacktrace;
}
}
}
MyPnPClass.java
public class MyPnPClass implements MyPnPInterface{
String doStuff(Properties props);
}
Now when you are working with many times you will need to dynamically generate
an instance of the generic type, there is a more simpler way to get this instance.
public class myClass<A as MyPnPInterface>{
private Class<a> getAClass(){
//When you are working with generics, those generics as part of the class as an array of arguments Class
clazz = ((Class<a>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
return clazz;
}
private A getA(){
return getAClass.newInstance();
}
}
How AWESOME is that? Now you can just instantiate the class with the generic
public MyClass<MyPnPInterface> myClazz = new MyClass<MyPnPClass>();

