且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时找不到 jar 中的类,但用于编译

更新时间:2023-11-16 23:36:10

我是否必须在运行 jar 时手动更改我的 shell 中的类路径以及在 ant 构建中更改它?

Do I have to manually change my classpath in my shell when running the jar as well as change it in the ant build?

是的,绝对.在编译时使类可用不会将该类嵌入到您的输出或类似的东西中.它只是让编译器可以使用它(找出存在哪些方法等).

Yes, absolutely. Making a class available at compile-time doesn't embed the class into your output or anything like that. It just makes it available to the compiler (to find out what methods are present etc).

如果我使用 java -cp j3d/*.jar -jar idv.jar 将 jar 添加到我的类路径中

If I add the jars to my classpath using java -cp j3d/*.jar -jar idv.jar

是的,它会 - 因为它被扩展为:

Yes, it would - because that's being expanded into:

java -cp j3d/foo.jar j3d/bar.jar ... -jar idv.jar

鉴于 本文档:

It's not clear to me whether -cp is meant to work at all with -jar, given this documentation:

使用此选项时,JAR 文件是所有用户类的来源,其他用户类路径设置将被忽略.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

一种选择是 在 jar 文件的清单中设置类路径本身.例如:

Class-Path: j3d/foo.jar j3d/bar.jar

另一种方法是暂时忽略 -jar 命令行选项,并使用:

Another would be to ignore the -jar command-line option for now, and use:

java -cp j3d/*:idv.jar your.class.name.Here

注意 * 而不是 *.jar,如文档所示:

Note the * rather than *.jar, as documented:

为了特别方便,包含基名 * 的类路径元素被认为等效于指定目录中所有扩展名为 .jar 或 .JAR 的文件的列表(java 程序无法区分两者之间的区别)调用).

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).