What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

前端 未结 15 2357
忘了有多久
忘了有多久 2020-11-21 05:27

What is the difference between NoClassDefFoundError and ClassNotFoundException?

What causes them to be thrown? How can they be resolved?

15条回答
  •  天涯浪人
    2020-11-21 06:11

    ClassNotFoundException is thrown when there is attempt to load the class by referencing it via a String. For example the parameter to in Class.forName() is a String, and this raises the potential of invalid binary names being passed to the classloader.

    The ClassNotFoundException is thrown when a potentially invalid binary name is encountered; for instance, if the class name has the '/' character, you are bound to get a ClassNotFoundException. It is also thrown when the directly referenced class is not available on the classpath.

    On the other hand, NoClassDefFoundError is thrown

    • when the actual physical representation of the class - the .class file is unavailable,
    • or the class been loaded already in a different classloader (usually a parent classloader would have loaded the class and hence the class cannot be loaded again),
    • or if an incompatible class definition has been found - the name in the class file does not match the requested name,
    • or (most importantly) if a dependent class cannot be located and loaded. In this case, the directly referenced class might have been located and loaded, but the dependent class is not available or cannot be loaded. This is a scenario where the directly referenced class can be loaded via a Class.forName or equivalent methods. This indicates a failure in linkage.

    In short, a NoClassDefFoundError is usually thrown on new() statements or method invocations that load a previously absent class (as opposed to the string-based loading of classes for ClassNotFoundException), when the classloader is unable to find or load the class definition(s).

    Eventually, it is upto the ClassLoader implementation to throw an instance of ClassNotFoundException when it is unable to load a class. Most custom classloader implementations perform this since they extend the URLClassLoader. Usually classloaders do not explicitly throw a NoClassDefFoundError on any of the method implementations - this exception is usually thrown from the JVM in the HotSpot compiler, and not by the classloader itself.

提交回复
热议问题