简体   繁体   English

Java URLClassLoader 在 eclipse 中工作,但在 cmd 中不起作用

[英]Java URLClassLoader works in eclipse but not in cmd

I have a program that tries to load java classes from a folder, using URLClassLoader.我有一个程序尝试使用 URLClassLoader 从文件夹加载 java 类。 The classloader is able to load the classes while running in eclipse, but when I try to run it in cmd it throws ClassNotFoundException.类加载器能够在 eclipse 中运行时加载类,但是当我尝试在 cmd 中运行它时,它会抛出 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.该程序需要两个参数: args[0] 根文件夹的绝对路径和要读取的测试文件夹的 args[1] 名称。

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.我可以在 eclipse 和 cmd 中使用此路径获取文件名。 Then I have my URLClassLoader.然后我有我的 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.这部分在 eclipse 中运行,但在 cmd 中抛出 ClassNotFound Exception。 In cmd the script is:在cmd中,脚本是:

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.我的猜测是类路径导致了问题,但我不太确定为什么 URLClassLoader 需要使用类路径而不是文件 url。

So I figure out that Eclipse automatically compile all the java classes under the default classpath folder.所以我发现Eclipse会自动编译默认classpath文件夹下的所有java类。 Reflection only works on the .class files created after compile, and that is why a ClassNotFound exception was thrown.反射仅适用于编译后创建的 .class 文件,这就是抛出 ClassNotFound 异常的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM