开发者

Why do I get a NoClassDefFoundError when trying to run my application?

Alright, so I was making a simple Java class that would simply print out "Hello!". Here 开发者_开发技巧is the code:

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

I compiled the class through the command prompt and then, when I wanted to run it, it gave me a NoClassDefFoundError suggesting that there is a problem with the classpath. That is really stupid since it is a one-class program. I tried many things but nothing seems to fix the problem.

How can I fix this?


You haven't shown how you ran the code. My guess is that you ran:

java Hello.class

which tries to run a class called Hello.class. The class is just named Hello, so you need:

java Hello

If you haven't set a CLASSPATH environment variable, that should be fine. Otherwise, either set it to a path including . or specify it on the command line:

java -cp . Hello

Of course, this is assuming you compiled the code first, using a command like this:

javac Hello.java


You have the environment variable CLASSPATH set, but it doesn't include a "." (dot) to represent the current directory (as the default does.) Run like this:

java -cp . Hello

That's "java space dash cp space dot space Hello".

Once you get past "Hello, World", you'll find that setting the class path becomes necessary all the time -- whether by hand like this (rarely, in the real world) or in a startup script, build tool, or IDE.

Use of the CLASSPATH environment variable is a bad practice leftover from Java's early days. Often you'll find that it's Apple's QuickTime installer that is setting it to something. You should never use or rely on this variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜