Java How to load classes out of a jar in the classpath with the System ClassLoader (no URLClassLoader)?

回眸只為那壹抹淺笑 提交于 2019-12-12 03:15:45

问题


So, I need to load some class at runtime with the System ClassLoader out of a jar in the classpath, but every time I try, I get a ClassNotFoundException. With the System ClassLoader, am I able to do just: x.y.classineed (x and y being packages) or would I have to do something like: pathtox.x.y.classineed, assuming it's even possible to do this?


回答1:


The JAR must not be in your CLASSPATH.

This works fine: I have the JDOM JAR in my CLASSPATH.

package cruft;

/**
 * ClassLoaderDemo
 * @author Michael
 * @since 2/9/12 7:09 PM
 * @link http://stackoverflow.com/questions/9220887/java-how-to-load-classes-out-of-a-jar-in-the-classpath-with-the-system-classload
 */
public class ClassLoaderDemo {
    public static void main(String[] args) {
        try {
            ClassLoader classLoader = ClassLoaderDemo.class.getClassLoader();
            if (classLoader != null) {
                Class clazz = classLoader.loadClass("org.jdom.Document");
                System.out.println(clazz.getName());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


来源:https://stackoverflow.com/questions/9220887/java-how-to-load-classes-out-of-a-jar-in-the-classpath-with-the-system-classload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!