実行時にクラスローダーを切り替えようとしています。
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を拡張するクラスであり、クラスの親に要求する前に、変更されたバージョンのクラスをロードする必要があります)
「アプローチ1」と「アプローチ2」の結果をまったく同じにしたいのですが、thread.setContextClassLoader(classLoader)は何も行わず、「アプローチ2」は常にシステムクラスローダーを使用しているようです(比較することで判断できます)。デバッグ中のtclおよびccl変数)。
新しいスレッドによってロードされたすべてのクラスに、指定されたクラスローダーを使用させることは可能ですか?