英文:
Java URLClassLoader works in eclipse but not in cmd
问题
以下是翻译好的部分:
我有一个程序,试图使用URLClassLoader从文件夹中加载Java类。在Eclipse中运行时,类加载器能够成功加载这些类,但是当我尝试在命令行中运行时,它会抛出ClassNotFoundException异常。
文件结构:
-rootFolder/
-src/
-tests/
-test1/
-A.java
该程序接受两个参数: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();
我能够使用这个路径获取文件名,在Eclipse和命令行中都可以。
然后是我的URLClassLoader部分。
URL[] urls = new URL[] {new File(rootString).toURI().toURL()};
URLClassLoader cl = new URLClassLoader(urls);
cl.loadClass("A"); // A是在文件中找到的名称,在默认包中
在Eclipse中,这部分可以正常运行,但在命令行中会抛出ClassNotFound异常。
在命令行中,脚本是这样的:
java -cp build/libs/project.jar project.Main rootFolder test1
我猜想问题可能出在类路径上,但我不太确定为什么URLClassLoader需要使用类路径而不是文件URL。
英文:
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.
答案1
得分: 0
所以我发现Eclipse会自动编译默认类路径文件夹下的所有Java类。反射仅对编译后创建的.class文件起作用,这就是为什么会抛出ClassNotFound异常。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论