如果 java Hello World 程序在包中,为什么我不能运行它?

2022-01-13 00:00:00 namespaces packages java

我创建了一个名为Hello.java"的文件,如下所示:

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!");
        }
}

我运行 javac Hello.java,然后运行 ​​java Hello,一切都按预期运行.

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

然后我将package testpackage;这一行添加到文件的顶部,并将其放在目录/home/matthew/Desktop/hellotest/testpackage中.我将 .:/home/matthew/Desktop/hellotest 放在我的 CLASSPATH 中,并以与以前相同的方式编译和运行.但是现在,我得到了这个错误:

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?

推荐答案

既然在testpackage里面,它的名字真的是testpackage.Hello.所以去一个目录并在上面执行 java.

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

相关文章