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

标签 java ant runtime java-3d compile-time

在我从一个 ant 文件构建这个项目后,我收到一个包含我构建的所有类的 jar。当我尝试运行这个 jar 时,出现以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/j3d/SceneGraphObject

此错误表明无法找到我正在使用的 jar 之一,特别是来自 java3d 的 j3dcore.jar。但是,当通过 ant build 编译到类文件中时,这个 jar 位于类路径中。

为什么这个类在运行时找不到,而在编译时却找到了?运行 jar 时是否必须在我的 shell 中手动更改我的类路径以及在 ant 构建中更改它?

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

我收到错误 Error: Could not find or load main class j3d.j3dutils.jar

最佳答案

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

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

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

是的,它会 - 因为它正在扩展为:

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

鉴于 this documentation,我不清楚 -cp 是否可以与 -jar 一起工作:

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

一个选项是 set the classpath within the manifest of the jar file itself .例如:

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

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

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

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

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

关于java - jar 中的类在运行时找不到,但用于编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561622/

相关文章:

java - Gradle 下的 JUnit 5 具有多个源集

java - Spring MVC 中的过滤器映射不适用于某些 URL

java - 用于补充不包括前导零二进制位的整数值的更好算法

ant - 如何使用 ANT(或其他一些构建系统,如果您愿意)构建 PDF LaTeX 文档?

algorithm - 这段代码在 Theta Notation 中的运行时间是多少?

java - Android GCM 无法实例化接收器

java - Protocol Buffers 可执行系统间 Linux 错误

java - 如何在 Ant 中使用带有 loadproperties 的 Base64 编码?

java - 执行外部程序

r - sapply 与复合函数的速度比较