问题
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