Alex Bollbach
Alex Bollbach

Reputation: 4570

Loading external class files without regard to class-paths or packages

I am attempting to load a class object from some compiled class file sitting in my Desktop dir.

I am feeding in two arguments to main in my program which uses URLClassLoader to get an instance of a class from a compiled file TheClassToLoad.class.

I have, in Main of the classLoading program: (args[0] is for something unrelated)

String classFile_FilePath = args[1];
String className = args[2];
URL classUrl = new URL(classFile_FilePath);
URLClassLoader ucl = new URLClassLoader(new URL[]{classUrl});

When running this program from the shell while in the project directory:

Me:ClassLoadingProgramRootDir Me$ java com.company.Main argZero file:///Users/Me/Desktop/ TheClassToLoad.class

I find a raised exception:

Exception in thread "main" java.lang.ClassNotFoundException: TheClassToLoad.class

So, there is a file TheClassToLoad.class in Desktop/ yet URLClassLoader raises an exception without providing the detail I need to debug the situation.

I am new to Java and am aware that class paths like com.company.Class is often needed to refer to a class's true class name based on package directory structure. However, in this case, I am simply requested that URLClassLoader give me an instance of the Class Object for an arbitrary compiled class file sitting somewhere on a machine.

Upvotes: 0

Views: 928

Answers (1)

Brett Kail
Brett Kail

Reputation: 33936

For URLClassLoader, the URL should be of the directory containing the class+package structure, not the class file itself. In your case, it should be file:///Users/Me/Desktop/.

The argument to loadClass should be the name of the class, not the name of the class file. In your case, it should be TheClassToLoad.

If the class is in a package (e.g., my.pkg.TheClassToLoad), then you should use that class name as the argument to loadClass, and the URL for URLClassLoader should still be the root of the package structure (e.g., file:///Users/Me/Desktop if the file is file:///Users/Me/Desktop/my/pkg/TheClassToLoad.class).

Upvotes: 1

Related Questions