Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

namespaces - Why can't I run my java Hello World program if it is inside a package?

I created a file called "Hello.java" that looks like this:

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

I ran javac Hello.java, then java Hello, and everything worked as expected.

I then added the line package testpackage; to the top of the file, and put it in the directory /home/matthew/Desktop/hellotest/testpackage. I put .:/home/matthew/Desktop/hellotest in my CLASSPATH, and compiled and ran the same way as before. But now, I get this error:

matthew@matthew-laptop:~/Desktop/hellotest/testpackage$ java Hello 
Exception in thread "main" java.lang.NoClassDefFoundError: Hello (wrong name: testpackage/Hello)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:334)
Could not find the main class: Hello. Program will exit.

Why did it work on its own, but not in a package?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now that it's in testpackage, its name is really testpackage.Hello. So go up a directory and do java on that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...