我有以下示例
public class Tester
{
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException
{
new Tester().execute();
}
private void execute() throws ClassNotFoundException
{
//Java Class Loader
ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
//Java custom Class Loader
ClassLoader customClassLoader = new CustomClassLoader();
Class<?> customClass = Class.forName("a.b.c.d.class", true, customClassLoader);
//Java custom Class Loader
ClassLoader customClassLoader = customClass.getClassLoader();
Thread.currentThread().setContextClassLoader(customClassLoader);
//Java custom Class Loader
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
//Java Class Loader?????
ClassLoader classLoader = this.getClass().getClassLoader();
}
}
为什么在调用后
Thread.currentThread().setContextClassLoader(customClassLoader);
一旦我执行
this.getClass().getClassLoader();
我仍然得到java类加载器,而不是我的自定义类加载器。
我该怎么做?
谢谢
Thread.setContextClassLoader
只是在Thread
中设置一个变量。链接类仍然是从每个类的类装入器完成的。它当然不会更改任何已加载类的类加载器。它更改的只是 Thread.getContextClassLoader
返回的类加载器。
我建议远离线程上下文类加载器和其他线程全局变量。