How to solve java.lang.NoClassDefFoundError?

前端 未结 27 1503
暗喜
暗喜 2020-11-21 06:04

I\'ve tried both the example in Oracle\'s Java Tutorials. They both compile fine, but at run-time, both come up with this error:

Exception in thread \"main\"         


        
27条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 06:34

    I'd like to correct the perspective of others on NoClassDefFoundError.

    NoClassDefFoundError can occur for multiple reasons like

    1. ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
    2. Class file located, but Exception raised while initializing static variables
    3. Class file located, Exception raised while initializing static blocks

    In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes jar file or to its package folder.

    What it means by saying "available in compile time"?

    • The referenced class is used in the code.
      Eg: Two classes, A and B(extends A). If B is referenced directly in the code, it is available at compile time, i.e. A a = new B();

    What it means by saying "not available at compile time"?

    • The compile time class and runtime class are different, i.e. for example base class is loaded using classname of child class for example Class.forName("classname")
      Eg: Two classes, A and B(extends A). Code has
      A a = Class.forName("B").newInstance();

提交回复
热议问题