How to solve java.lang.NoClassDefFoundError?

前端 未结 27 1509
暗喜
暗喜 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:46

    No Class Definition Exception occurs when the intended class is not found in the Class Path. At Compile Time Class : Class was generated from Java Compiler, But Somehow at Run Time the Dependent Class is not found.

    Lets go through one Simple Example :

    public class ClassA{
    public static void main(String args[]){
         //Some gibberish Code...
         String text = ClassB.getString();
         System.out.println("Text is :" + text);
    }
    

    }

    public class ClassB{
        public static String getString(){
          return "Testing Some Exception";
     }
    }
    

    Now Lets assume that the above two Java Source Code are placed in some Folder let say "NoClassDefinationFoundExceptionDemo"

    Now open a shell(Assuming Java is already being setup correctly)

    1. Go to Folder "NoClassDefinationFoundExceptionDemo"
    2. Compile Java Source Files javac ClassB javac ClassA
    3. Both Files are Compiled Sucessfully and generated Class files in the same Folder as ClassA.class and ClassB.class
    4. Now Since we are overiding ClassPath to current working directory therefore we execute the following command java -cp . ClassA and It worked Successfully and you will see the Output in the screen
    5. Now Lets say, You removed ClassB.class file from Present Directory. and now you execute the command again. java -cp . ClassA Now it will greet you with NoClassDefFoundException. as ClassB which is a dependency for ClassA is not found in the classpath(i.e present working directory).

提交回复
热议问题