解决Java中的NoClassDefFoundError问题 [英] Troubleshoot NoClassDefFoundError in Java

查看:140
本文介绍了解决Java中的NoClassDefFoundError问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Main.java的Java程序,它位于以下目录中:

I have a Java program called Main.java, it is located in the following directory:

/home/user/program/Main.java

当我尝试从'program'目录运行Main.java时,一切好的,我使用这一行:

When I try to run Main.java from the 'program' directory, everything goes ok, I use this line:

/home/user/program$ java Main

但是当我尝试从主目录运行Main.java时:

But when I try to run Main.java from the home directory :

/home$ java /home/user/program/Main

I获取:

Exception in thread "main" java.lang.NoClassDefFoundError: /home/user/program/Main
Caused by: java.lang.ClassNotFoundException: .home.user.program.Main

原因是什么这个错误?

推荐答案

这是由于你的类路径,它将默认为当前目录。从 / home / user / program 运行 java Main 时,它会在当前目录中找到该类(因为该包似乎没有设置,这意味着它是默认的)。因此,它在 /home/user/program/Main.class 中找到该类。

This is due to your classpath, which will default to the current directory. When you run java Main from /home/user/program it finds the class in the current directory (since the package seems to be unset, meaning it is the default). Hence, it finds the class in /home/user/program/Main.class.

运行 java / home / user / program / Main / home 尝试在类路径(当前目录)中查找将要使用的类查看 / home / home / user / program 期望找到包含<的定义的文件 Main.class code>主类,包 .home.user.program

Running java /home/user/program/Main from /home tries to find the class in the classpath (the current directory) which will look in /home/home/user/program expecting to find the file Main.class containing a definition of the Main class with package .home.user.program.


额外的细节:我认为java
启动器试图通过
转换/ -notation为类名
转换为。-符号;当你运行
java / home / user / program / Main 时实际运行的是
java
。 home.user.program.Main
为你服务。这个
是因为你不应该指定
一个文件,而是一个完全指定的
类名(即包括
说明符包)。当一个类有一个包
时,java期望在
类路径中的目录(或jar)中找到与
名称相匹配的
目录结构中的类;因此,它将尝试查看
/ home / home / user / program 的类文件

Extra detail: I think the java launcher is trying to be nice by converting /-notation for a classname to the .-notation; and when you run java /home/user/program/Main it is actually running java .home.user.program.Main for you. This is because you shouldn't be specifying a file, but a fully specified classname (ie including package specifier). And when a class has a package java expects to find that class within a directory structure that matches the package name, inside a directory (or jar) in the classpath; hence, it will try to look in /home/home/user/program for the class file

您可以通过使用 -cp -classpath 指定类路径来修复它:

You can fix it by specifying your classpath with -cp or -classpath:

java -cp /home/user/program Main

这篇关于解决Java中的NoClassDefFoundError问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆