How to use URLClassLoader to load a *.class file?

Posted by DeletedAccount on Stack Overflow See other posts from Stack Overflow or by DeletedAccount
Published on 2009-04-10T18:10:32Z Indexed on 2010/05/19 10:30 UTC
Read the original article Hit count: 389

Filed under:
|

I'm playing around with Reflection and I thought I'd make something which loads a class and prints the names of all fields in the class. I've made a small hello world type of class to have something to inspect:

kent@rat:~/eclipsews/SmallExample/bin$ ls
IndependentClass.class
kent@rat:~/eclipsews/SmallExample/bin$ java IndependentClass 
Hello! Goodbye!
kent@rat:~/eclipsews/SmallExample/bin$ pwd
/home/kent/eclipsews/SmallExample/bin
kent@rat:~/eclipsews/SmallExample/bin$

Based on the above I draw two conclusions:

  • It exists at /home/kent/eclipsews/SmallExample/bin/IndependentClass.class
  • It works! (So it must be a proper .class-file which can be loaded by a class loader)

Then the code which is to use Reflection: (Line which causes an exception is marked)

import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class InspectClass {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
    	URL classUrl;
    	classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/IndependentClass.class");
    	URL[] classUrls = { classUrl };
    	URLClassLoader ucl = new URLClassLoader(classUrls);
    	Class c = ucl.loadClass("IndependentClass"); // LINE 14
    	for(Field f: c.getDeclaredFields()) {
    		System.out.println("Field name" + f.getName());
    	}
    }
}

But when I run it I get:

Exception in thread "main" java.lang.ClassNotFoundException: IndependentClass
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at InspectClass.main(InspectClass.java:14)

My questions:

  1. What am I doing wrong above? How do I fix it?
  2. Is there a way to load several class files and iterate over them?

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection