[英]How to reload a loaded class with different ClassLoader in Java?
public class ClassScanner
{
// scan extraClasspath for specific classes
public List<Class<?>> scanClasspathForClass(String scanCriteria)
{
...
}
public static Class<?> reloadClass(Class<?> clazz, ClassLoader clazzLoader)
{
// Question: how to reload a loaded class (ClassScanner in this example) with a different arbitrary ClassLoader?
}
// an example of how reloadClass() would be used
// in real case, this function would be in different class
public List<Class<?>> scan(URL[] extraClasspath)
{
URLClassLoader urlClazzLoader = new URLClassLoader(extraClasspath, null);
Class<?> newClass = reloadClass(ClassScanner.class, urlClazzLoader);
return ((ClassScanner) newClass.newInstance()).scanClasspathForClass();
}
}
Above code demonstrates the question and why it is a question. 上面的代码演示了问题以及为什么是问题。 I need to implement reloadClass()
. 我需要实现reloadClass()
。 I wonder if there is a reliable solution in Java 1.6. 我想知道Java 1.6中是否有可靠的解决方案。 One useful reference would be Find where java class is loaded from . 一个有用的参考是查找从中加载java类的位置 。
Thanks for help! 感谢帮助!
Found myself the answer from http://www2.sys-con.com/itsg/virtualcd/java/archives/0808/chaudhri/index.html . 从http://www2.sys-con.com/itsg/virtualcd/java/archives/0808/chaudhri/index.html找到了答案。
Basically what I need is to make one ClassLoader A to share its namespace with another ClassLoader B. The way I found to achieve this is to use the ClassLoader parent-delegation model. 基本上,我需要使一个ClassLoader A与另一个ClassLoader B共享其名称空间。我发现实现此目标的方法是使用ClassLoader父委托模型。 Here, ClassLoader A is the parent ClassLoader. 在这里,ClassLoader A是父ClassLoader。
public List<Class<?>> scan(URL[] extraClasspath) throws Exception
{
URLClassLoader urlClazzLoader = new URLClassLoader(extraClasspath, ClassScanner.class.getClassLoader());
return urlClazzLoader.loadClass(ClassScanner.getName()).newInstance();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.