0

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.

1
  • 1
    If your class has a 'package' statement, you need to respect it when you try to load and use it.
    – bmargulies
    Apr 9, 2016 at 18:50

1 Answer 1

1

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).

1
  • thank you, not using the "fully specifying" class name was the root cause Apr 11, 2016 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.