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 {
String currentDirectory = new java.io.File( "." ).getCanonicalPath().replace("bin", "");
String pathToClassFiles = currentDirectory + "/webapps/wb5/WEB-INF/classes";
String pathToClassFile = pathToClassFiles + "/" + canonicalName.replace(".", "/") + ".class";
File file = new File(pathToClassFile);
@SuppressWarnings("deprecation")
URL myUrl = file.toURL();
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
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. The next time I need to created an instance I dont have to reload the .class from the disk again. How can I avoid this?
Aucun commentaire:
Enregistrer un commentaire