0

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?

Josh
  • 83
  • 10
  • 1
    *"I need to load some class at runtime with the System ClassLoader out of a jar in the classpath,"* Why? What is it you are actually trying to achieve? – Andrew Thompson Feb 10 '12 at 00:48

1 Answers1

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();
        }
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • +1 for using the Class's ClassLoader. Using the System classloader is almost never the right decision. – Dev Feb 10 '12 at 01:13