Opening class in package from console in Java

2020-05-07 01:00发布

问题:

So when i try to open a java class that's not in a package from the command prompt it all works fine, but when I try to open a class that's in a package it gives me NoClassDefFoundError. And when I list the package when I try to open the class (java somepackage/someclass) it says that it can't load or find the main class.

Any help?

回答1:

What I can infer is, you have two classes:

Test.java:

// no package defined here

class Test{
    public static void main(String[] args){
        System.out.println("Test");
    }
}

so you can compile and run it using:

javac Test.java
java Test

Another class:

Test.java:

package test; // package defined here

class Test{
    public static void main(String[] args){
        System.out.println("Test");
    }
}

And thus doing same thing gives you error. For this you need to be in the parent directory of 'test' folder in your terminal or cmd and use:

java test.Test

No problem with compiler. You can compile as usual using javac Test.java from inside 'test' folder.



回答2:

NoClassDefFoundError means that your JVM can't find your class at runtime. This could be because it's not visible (set to private or protected, or just no access modifier).

It could also be missing from your build path