现在的位置: 首页 > 编程技术 > Java > 正文

NoClassDefFoundError和ClassNotFoundException区别

2017年09月22日 Java ⁄ 共 2166字 ⁄ 字号 NoClassDefFoundError和ClassNotFoundException区别已关闭评论 ⁄ 阅读 824 次

看源码的定义

NoClassDefFoundError

/**

* Thrown if the Java Virtual Machine or a <code>ClassLoader</code> instance

* tries to load in the definition of a class (as part of a normal method call

* or as part of creating a new instance using the <code>new</code> expression)

* and no definition of the class could be found.

* <p>

* The searched-for class definition existed when the currently

* executing class was compiled, but the definition can no longer be

* found.

*

* @author  unascribed

* @since   JDK1.0

*/

 

ClassNotFoundException

/**

* Thrown when an application tries to load in a class through its

* string name using:

* <ul>

* <li>The <code>forName</code> method in class <code>Class</code>.

* <li>The <code>findSystemClass</code> method in class

*     <code>ClassLoader</code> .

* <li>The <code>loadClass</code> method in class <code>ClassLoader</code>.

* </ul>

* <p>

* but no definition for the class with the specified name could be found.

*

* <p>As of release 1.4, this exception has been retrofitted to conform to

* the general purpose exception-chaining mechanism.  The "optional exception

* that was raised while loading the class" that may be provided at

* construction time and accessed via the {@link #getException()} method is

* now known as the <i>cause</i>, and may be accessed via the {@link

* Throwable#getCause()} method, as well as the aforementioned "legacy method."

*

* @author  unascribed

* @see     java.lang.Class#forName(java.lang.String)

* @see     java.lang.ClassLoader#findSystemClass(java.lang.String)

* @see     java.lang.ClassLoader#loadClass(java.lang.String, boolean)

* @since   JDK1.0

*/

 

 

ClassNotFoundException这个错误,比较常见也好理解。

原因:就是找不到指定的class。主要是编译时错误

常见的场景就是:

1 调用class的forName方法时,找不到指定的类

2 ClassLoader 中的 findSystemClass() 方法时,找不到指定的类

3 ClassLoader 中的 loadClass() 方法时,找不到指定的类

 

package com.jiangwenrou;

public class ClassNotF {

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

Class.forName("com.jiangwenrou.ClassNotF1");

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

 

NoClassDefFoundError错误的发生,是因为Java虚拟机在编译时能找到合适的类,而在运行时不能找到合适的类导致的错误。例如在运行时我们想调用某个类的方法或者访问这个类的静态成员的时候,发现这个类不可用,此时Java虚拟机就会抛出NoClassDefFoundError错误。与ClassNotFoundException的不同在于,这个错误发生只在运行时需要加载对应的类不成功,而不是编译时发生。

ClassNotFoundException比NoClassDefFoundError容易解决,是因为在编译时我们就知道错误发生,并且完全是由于环境的问题导致。而如果你在J2EE的环境下工作,并且得到NoClassDefFoundError的异常,而且对应的错误的类是确实存在的,这说明这个类对于类加载器来说,可能是不可见的。

抱歉!评论已关闭.