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
140 views
in Technique[技术] by (71.8m points)

How do I run a Java class in a package?

I have two java classes as follows

App1 without a package:

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

App2 in a package:

package java.java.package1;    
class App2 {
    public static void main(String[] args) {
        System.out.println("App2 hello world...");
    }
}

I can compile them both:

D:javaTest>javac App1.java

D:javaTest>javac App2.java

However, I can only run the first one:

D:javaTest>java App1
App1 hello world...

D:javaTest>java java.java.package1.App2

Exception in thread "main" java.lang.NoClassDefFoundError: java/java/package1/App2
Caused by: java.lang.ClassNotFoundException: java.java.package1.App2
        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)
Could not find the main class: java.java.package1.App2.  Program will exit.

How can I run App2?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you put the source in an appropriate directory hierarchy matching the package name (D:javaTestjavajavapackage1App1.java), and compile/run from the root of the hierarchy (D:javaTest), you wouldn't have this problem:

D:javaTest>javac javajavapackage1App1.java

D:javaTest>java java.java.package1.App1
App2 hello world...

You can also compile using the -d option so that the classes are moved into such a directory hierarchy:

javac -d . App2.java
java java.java.package1.App2

Note you shouldn't use a package name starting with java, and later versions of the JDK will throw a SecurityException. See this question for more information.


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

...