我创建了一个CustomClassLoader,它继承自ClassLoader以覆盖loadClass方法。
以下是新的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;
}
}
要从磁盘重新加载特定类,我就是这样做的
ClassLoader parentClassLoader = DesignFactory.class.getClassLoader();
DesignFactoryClassLoader designFactoryClassLoader = new DesignFactoryClassLoader(parentClassLoader);
designFactoryClassLoader.classCanonicalName = classCanonicalName;
Class reloadedCls = designFactoryClassLoader.loadClass(classCanonicalName);
我现在遇到的问题是:当MyClass.class被修改后我需要创建一个MyClass实例时,我使用CustomClassLoader创建它,并且.class文件已经加载到customClassLoader中。第二次我需要创建一个实例,我将使用我的逻辑从磁盘重新加载.class文件。我怎么能避免这个?