gpt4 book ai didi

java - 尝试查找 Java 包时,通过命令行编译和执行显示 NoClassDefFoundError

转载 作者:行者123 更新时间:2023-12-04 06:52:11 25 4
gpt4 key购买 nike

我有一个尝试发送和接收对象的客户端/服务器程序。

一共有三个包:服务器、客户端和共享
shared 只包含 Message 类

我将共享包中的 Message.java 放入与 calcclient 包源文件和 calcserver 包源文件相同的文件夹中。

我使用以下行进行编译: javac -classpath .; (客户端或 server.java 文件的长列表) Message.java
他们可以编译。
然后我将目录向上一级更改并运行: java -classpath .; 。主要的

当我使用 Netbeans 运行时,整个程序正常运行。但如果我从命令行运行,则不会。如果它通过命令行执行,程序将一直运行,直到需要使用 Message 对象。然后它会显示一个 NoClassDefFoundError

我是否将正确的文件放在正确的位置?如何让程序通过命令行查找共享包?

最佳答案

文件不在正确的位置。 Message 类属于不同的包,因此它不应与其他类共存。来自 http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html :

User classes are classes which build on the Java platform. To find user classes, the launcher refers to the user class path -- a list of directories, JAR archives, and ZIP archives which contain class files.

A class file has a subpath name that reflects the class's fully-qualified name. For example, if the class com.mypackage.MyClass is stored under /myclasses, then /myclasses must be in the user class path and the full path to the class file must be /myclasses/com/mypackage/MyClass.class. If the class is stored in an archive named myclasses.jar, then myclasses.jar must be in the user class path, and the class file must be stored in the archive as com/mypackage/MyClass.class.



你有几个选择:

最好的解决办法是花时间学习 Ant。 Netbeans 项目是用 Ant 构建的,这是我书中 Netbeans 的一个非常棒的特性,您可以打开项目中的 build.xml 并找到有关 Netbeans 为构建您的项目所做的工作的合理注释描述。我真的不认为有很多地方可以从命令行运行构建,所以学习 Ant 之类的东西会很有帮助。

更复杂的下一个级别是为您的共享包手动构建一个 Jar 并将其放在类路径中的某个位置。

最基本的方法就是将 java 文件编译成类文件,并将它们放在反射(reflect)包名称的适当目录中,如上面引用中所述。

关于java - 尝试查找 Java 包时,通过命令行编译和执行显示 NoClassDefFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2954756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com