简体   繁体   English

Java如何使用System ClassLoader(无URLClassLoader)从类路径中的jar中加载类?

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

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. 因此,我需要在运行时使用System ClassLoader从类路径中的jar中加载一些类,但是每次尝试时,我都会收到ClassNotFoundException。 With the System ClassLoader, am I able to do just: xyclassineed (x and y being packages) or would I have to do something like: pathtox.xyclassineed, assuming it's even possible to do this? 使用System ClassLoader,我是否可以做:xyclassineed(x和y是包),或者假设有可能做些类似的事情:pathtox.xyclassineed?

The JAR must not be in your CLASSPATH. JAR不得位于您的CLASSPATH中。

This works fine: I have the JDOM JAR in my CLASSPATH. 效果很好:我的CLASSPATH中有JDOM JAR。

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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM