LINUX下执行.class的java.lang.NoClassDefFoundError解决
Posted yangzongzhuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LINUX下执行.class的java.lang.NoClassDefFoundError解决相关的知识,希望对你有一定的参考价值。
一个老外的帖子说的还比较详细:Most people always have the following problem when run their java programs under linux box:
Exception in thread "main" java.lang.NoClassDefFoundError: *.java
Even though these programs really have no problem at all.
Here are some solutions for you:
1) Check your syntax that you are trying to run the java class and make sure it should be like this (assume the class file is foo.class):
java foo instead of java foo.class
2) Make sure your classpath contain the special path ".", actually this is most likely where the problem come from.
You can try to run your program as follows.
java -cp . foo or
java -classpath . foo
If it works, then you are suppose to add "." to you classpath.
For example:
export CLASSPATH=.:$JAVA_HOME/lib:JAVA_HOME/jre/lib
3) Check it out if you compiled the java file without specifying the package that import in your file.
What if all these works are done, but your still got the same problem?
Well, in this case, you've got to have a look at your souce code......
Good luck!
前两点虽然有时也导致这个问题, 但是不是问题的关键, 关键是第三点~
但这个家伙的第三点说的很模糊..还好运! 不过倒是起到提示作用~
研究了下, 发现出现这个问题多是由于源代码里面有package名:
源码路径: /home/ymiao/linux_java_project/src
测试代码:
package test;
public class HelloWorld
/**
* @param args
*/
public static void main(String[] args)
// TODO Auto-generated method stub
System.out.println("HelloWorld!");
字节码文件输出路径: /home/ymiao/linux_java_project/classes
字节码文件所在路径: /home/ymiao/linux_java_project/classes/test/
这个路径下面是HelloWorld.class文件
执行:
1. 如果跑到/home/ymiao/linux_java_project/classes/test/
执行java HelloWorld
输出:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: test/HelloWorld)
2. 如果跑到/home/ymiao/linux_java_project/classes/test/
执行java test.HelloWorld
输出:
Exception in thread "main" java.lang.NoClassDefFoundError: test/HelloWorld
3. 如果跑到/home/ymiao/linux_java_project/classes
执行java test.HelloWorld
输出:
HelloWorld!
结论:
1. 出现wrong name的java.lang.NoClassDefFoundError, 由于执行的时候前面没加package名,
否则就是classpath路径不对, 要指定-cp或者-classpath为字节码输出路径(注意不是字节码文件所在路径, 由于package的存在).
2. 项目中的classpath是Default output folder字节码文件输出路径,而不是字节码文件所在路径
完整的执行命令是:
java -cp 字节码文件输出路径 字节码文件的全名(包名.类名,default package没有包名)
java -cp /home/ymiao/linux_java_project/classes test.HelloWorld
以上是关于LINUX下执行.class的java.lang.NoClassDefFoundError解决的主要内容,如果未能解决你的问题,请参考以下文章