I have created a CustomClassLoader that inherits from the ClassLoader to override loadClass method.
Below is the new CustomClassLoaded
public class DesignFactoryClassLoader extends ClassLoader{
public DesignFactoryClassLoader(ClassLoader parent) {
super(parent);
}
public String classCanonicalName= null;
public Class loadClass(String canonicalName) throws ClassNotFoundException {
if(!this.classCanonicalName.equals(canonicalName))
return super.loadClass(canonicalName);
try {
URL classLoadUrl = new URL(this.reloadClassUrl);
URLConnection connection = classLoadUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
int data = input.read();
while(data != -1){
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
return defineClass(canonicalName,
classData, 0, classData.length);
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
To reload a particular class from the disk this is how I do it
ClassLoader parentClassLoader = DesignFactory.class.getClassLoader();
DesignFactoryClassLoader designFactoryClassLoader = new DesignFactoryClassLoader(parentClassLoader);
designFactoryClassLoader.classCanonicalName = classCanonicalName;
Class reloadedCls = designFactoryClassLoader.loadClass(classCanonicalName);
The problem that I now have is: When I needed to create an instance of MyClass after the MyClass.class has been modified I created it using the CustomClassLoader and the .class file has been loaded into the customClassLoader. The second time I need to create an instance I will reload the .class file again from the disk with my logic. How can I avoid this?