java ClassNotFoundException and NoClassDefFoundError 的区别

来源:互联网 发布:东方网络 编辑:程序博客网 时间:2024/05/20 06:30

很多时候我们经常会遇到这两个错误或异常,虽然他们都和classpath的设置有关,但是他们是不相同的。

1:ClassNotFoundException的出现是因为当我们在运行期间通过Class.forName() orClassLoader.loadClass() or ClassLoader.findSystemClass() 等方法动态加载类的时候,在jvm中找不到对应的类,所以就会出现该异常,这个异常可以通过try catch方法捕获处理。

2:NoClassDefFoundError 是通过new的形式去生成类实例的,在编译期间是存在的,但是在运行的时候找不到该类,这也就是为什么可以正常的编译,但是不能运行的原因。一般而言该错误比ClassNotFoundException容易解决,因为其在编译期间是存在的。

NoClassDefFoundError 解决的三种方法:

1. Simple example of NoClassDefFoundError is class belongs to a jar and jar was not added into classpath or sometime jar’s name has been changed by someone like in my case one of my colleague has changed tibco.jar into tibco_v3.jar and by program is failing with java.lang.NoClassDefFoundError and I was wondering what’s wrong.

首先是类在运行的时候依赖于其它的一个jar包,但是该jar包没有加载到classpath中或者是该jar包的名字被其他人改了,就像我的一个例子tibo.jar改为了tibco_v3.jar…….

2. Class is not in Classpath, there is no sure shot way of knowing it but many a times you can just have a look to print System.getproperty(”java.classpath“)and it will print the classpath from there you can at least get an idea of your actual runtime classpath.

运行的类不在classpath中,这个问题没有一个确定的方法去知道,但是很多时候你可以通过System.getproperty(”java.classpath“)方法,该方法能让你至少可以领略到实际存在的运行期间的classpath。

 
3. Just try to run with explicitly -classpath option with the classpath you think will work and if its working then it’s sure short sign that some one is overriding java classpath.

试着通过-classpath命令明确指出你认为正确的classpath,如果能够正常执行的话就说明你使用的classpath是正确的,而系统中的classpath已经被修该过了。

转自:http://scnblogs.techweb.com.cn/ericxl/archives/51.html