【问题标题】:ClassLoader classes are not properly loaded in the threadClassLoader 类未在线程中正确加载
【发布时间】:2015-07-12 04:41:32
【问题描述】:

我正在使用 URLClassLoader 创建一个新的类加载器,并尝试将其设置为当前线程的类加载器。 但它不适合我。 根据我的理解,如果我给当前线程设置了一个classLoader,那么当前线程引用的方法和接口应该来自当前的classLoader。 但我的情况并非如此。该方法是从另一个 jar 中提取的,我得到了 classCastExecption。 下面是获取classLoader的代码:

    public ClassLoader getClassLoader(boolean b) {

    ClassLoader loader = null;
    File file = new File(SamVariables.JAR_FILE);
    if (file.exists()){


                try {
            List<URL> urlsList = new ArrayList<URL>();
            urlsList.add(file.toURI().toURL());
            URL[] urls = new URL[urlsList.size()];
            urlsList.toArray(urls);
            URLClassLoader url = new URLClassLoader(urls);


            try { 
                loader = Class.forName("org.jboss.naming.remote.client.InitialContextFactory", false, url).getClassLoader();  

            } catch (ClassNotFoundException e) {
                loader = Class.forName("org.jboss.jms.client.JBossConnectionFactory", false, url).getClassLoader(); 
            }
            } 

        } catch (Throwable e) {
            e.printStackTrace();
        } 

    }   
    return loader; // I am successfully getting the classLoader for the class

}

I set it to the current thread

    Thread.currentThread().setContextClassLoader(getClassLoader);

But later when I try to get the topicConnectionFactory object, it gives me typecast exception:

topicConnectionFactory = (TopicConnectionFactory) topicConnectionFactObj;

它给了我 classCastException。

当我检查 TopicConnectionFactory 对象时,它来自另一个导致问题的 jar 文件。

【问题讨论】:

    标签: java jar jboss casting classloader


    【解决方案1】:

    据我了解,如果我为当前线程设置了一个类加载器, 当前线程引用的方法和接口应该是 来自当前的类加载器。

    不,这是一种误解。除非代码专门使用它,否则不会使用上下文类加载器。特别是,JVM 不使用上下文类加载器(但特定 API 使用它,例如用于查找 XML 解析器实现)。而是使用原始类的类加载器。

    如果您希望您的代码能够从自定义类加载器加载类,那么您必须在该类加载器中加载您的类。例如,将这些类放在一个单独的 JAR 中,将该 JAR 放在 URLClassLoader 类路径中,然后使用反射从该 URLClassLoader 加载/调用您的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多