简体   繁体   中英

Class declaration bug (NoClassDefFoundError caused by ClassNotFoundException)

Please advise me what's wrong with this class declaration:

ExchEngine.java

package engine;

public class ExchEngine {

    public ExchEngine() {
    }

    public static void main(String[] args) {

        ExchEngine engine = new ExchEngine();

    }
}

When I compile this file, I always get exception:

java.lang.NoClassDefFoundError: test_engine/ExchEngine
Caused by: java.lang.ClassNotFoundException: test_engine.ExchEngine
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Exception in thread "main"

This seems very weird that ExchEngine.java is inside a package and it cannot run itself. Thanks for any help.

You should put your source file in a directory called "engine", since that's the package name of gave it.

Compile the file with javac engine/ExchEngine.java and run it with java engine.ExchEngine .

Your class is engine.ExchEngine . Something somewhere is looking for test_engine.ExchEngine , and is causing this error when it fails to do so. You presumably need to change the two so that they match.

This isn't a compile time problem, it is a run time error.

Need more information. For instance, how are you trying to run it? In Eclipse?

If in Eclipse: You may need to clean the project. Or you might be trying an old run configuration from before you changed the package.

Specify the classpath when running your application

Assuming after compiling, you have the following directory structure:

./test_engine/ExchEngine.class

then run it like so:

java -cp . test_engine.ExchEngine

If your using an IDE, reconfigure the project, mainly where it looks for the Main method. Clean, rebuild, restart, do what ever you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM