Loading classes with unknown names
1 posts in topic
Flat View  Flat View

Posted By:   Michael_Wax
Posted On:   Tuesday, December 18, 2001 03:08 PM

How do I load a class without the fully qualified name?

Example: I am traversing a directory structure, and find a file (called "MyClass") which I know to be a class. However, I do not know the package name of the class, so I cannot call Class.forName(package + ".MyClass"). How can I load the class, which I then will interrogate to find the package name>

Re: Loading classes with unknown names

Posted By:   Christopher_Schultz  
Posted On:   Wednesday, December 19, 2001 07:18 AM

Well, there are at least two ways to do this:

  1. Take a look at The Java Virtual Machine Specification, specifically chapter 4, "The Class File Format".

    This will show you that if you open a class file as a stream of bytes, then read the file until you get to the this_class index, you can obtain the fully qualified name of the class. The this_class index is an integer index into the constant pool which is an array. The array index that this_index will point to will be a "class" entry, which has an index to the string which represents its name.

    The name will look like "java/lang/String", so you'll have to convert the forward slashes to dots.

  2. Since a class must be accessable from the CLASSPATH, it seems reasonable that you can try educated guesses at the fully qualified class name.

    Take a look at the path to the class file in question. Take a look at each component of the CLASSPATH. My guess is that you could try a number of possibilities and try to load the class each time. If you succeed, fine. If you don't try another combination.

    Here's an example:

    CLASSPATH = /usr/local/classes:/home/me/classes

    Path to class file: /home/me/classes/com/myapp/util/Utils.class

    If you loop through the pieces of the CLASSPATH, you'll notice that the path to the class file starts with the second CLASSPATH entry. Since this is the case, try chopping-off that beginning string, and you're left with:


    Now, eliminate the leading "/" and the ".class" from the end of the String. Convert "/" to "." and attempt to load the class.

    In this contrived example, you're good to go. My guess is that this will work more often than not.

Good luck,
About | Sitemap | Contact