【发布时间】:2014-08-26 05:17:10
【问题描述】:
我正在尝试在运行时切换类加载器:
public class Test {
public static void main(String[] args) throws Exception {
final InjectingClassLoader classLoader = new InjectingClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
Thread thread = new Thread("test") {
public void run() {
System.out.println("running...");
// approach 1
ClassLoader cl = TestProxy.class.getClassLoader();
try {
Class c = classLoader.loadClass("classloader.TestProxy");
Object o = c.newInstance();
c.getMethod("test", new Class[] {}).invoke(o);
} catch (Exception e) {
e.printStackTrace();
}
// approach 2
new TestProxy().test();
};
};
thread.setContextClassLoader(classLoader);
thread.start();
}
}
和:
public class TestProxy {
public void test() {
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
ClassLoader ccl = ClassToLoad.class.getClassLoader();
ClassToLoad classToLoad = new ClassToLoad();
}
}
(InjectingClassLoader 是一个扩展了 org.apache.bcel.util.ClassLoader 的类,它应该在询问它的父类之前加载类的修改版本) p>
我想让“方法 1”和“方法 2”的结果完全相同,但看起来 thread.setContextClassLoader(classLoader) 什么都不做,而“方法 2”总是使用系统类加载器(可以通过调试时比较tcl和ccl变量来确定)。
是否可以让新线程加载的所有类使用给定的类加载器?
【问题讨论】:
标签: java reflection multithreading classloader bcel