Search code examples
javaeclipsecmdclassloaderurlclassloader

Java URLClassLoader works in eclipse but not in cmd


I have a program that tries to load java classes from a folder, using URLClassLoader. The classloader is able to load the classes while running in eclipse, but when I try to run it in cmd it throws ClassNotFoundException.

File structure:

-rootFolder/
  -src/
  -tests/
    -test1/
      -A.java

The program takes two arguments: args[0] the absolute path of the root folder and args[1] name of the test folder to read.

String rootString = args[0]+ File.separator + "tests" + File.separator + args[1] + File.separator;
File folder = new File(rootString);
String[] files = folder.list();

I am able to get the file names using this path, both in eclipse and cmd. Then I have my URLClassLoader.

URL[] urls = new URL[] {new File(rootString).toURI().toURL()};
URLClassLoader cl = new URLClassLoader(urls);
cl.loadClass("A"); // A is the name found in files, in default package

This part runs in eclipse but throw ClassNotFound Exception in cmd. In cmd the script is:

java -cp build/libs/project.jar project.Main rootFolder test1

My guess is that the classpath causes the issue but I am not very sure why URLClassLoader needs to use classpath instead of file urls.


Solution

  • So I figure out that Eclipse automatically compile all the java classes under the default classpath folder. Reflection only works on the .class files created after compile, and that is why a ClassNotFound exception was thrown.