Compiling Java program with javac succeeds, but NoClassDefFoundError on run

倾然丶 夕夏残阳落幕 提交于 2021-01-27 06:32:33

问题


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

Command prompt session:

C:\Users\zobdos\Desktop>javac HelloWorld.java

C:\Users\zobdos\Desktop>dir *.class
 Volume in drive C is OS
 Volume Serial Number is A45E-7B01

 Directory of C:\Users\zobdos\Desktop

11/20/2010  10:16 AM               417 HelloWorld.class
               1 File(s)            417 bytes
               0 Dir(s)   8,145,432,576 bytes free

C:\Users\zobdos\Desktop>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: HelloWorld.  Program will exit.

C:\Users\btolbert\Desktop>

回答1:


You've a %CLASSPATH% environment variable in your environment. Get rid of it, it's disturbing your java commands, it's a poor practice tought by Sun Oracle anyway. Once you use -classpath argument or its -cp shorthand, then the %CLASSPATH% will be overridden. If the classpath is not specified by either the environment variable or the arguments, then the current path will be taken as default (as you initially expected).




回答2:


Nevermind, it works after using:

java -classpath . HelloWorld



回答3:


run with classpath specified to the current directory:

java -cp . HelloWorld


来源:https://stackoverflow.com/questions/4233679/compiling-java-program-with-javac-succeeds-but-noclassdeffounderror-on-run

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!