2

我有以下示例

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 类加载器,而不是我的自定义类加载器。

我怎么能做到这一点?

谢谢

4

1 回答 1

0

Thread.setContextClassLoader只需在Thread. 链接类仍然是从每个类的类加载器完成的。它当然不会更改任何已加载类的类加载器。它所改变的只是由Thread.getContextClassLoader.

我建议远离线程上下文类加载器和其他线程全局变量。

于 2012-04-19T09:14:40.833 回答