gezhonglunta gezhonglunta - 1 month ago 6
Java Question

how to run the java class with has package name

I have the two java class as follows:

1.

none package class
System.out.println("App1 hello world...");


2.

has package
package java.java.package1;

System.out.println("App1 hello world...");


then,I compile and run them,the result as follows:

D:\javaTest>javac App1.java

D:\javaTest>javac App2.java

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

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

Exception in thread "main" java.lang.NoClassDefFoundError: java/java/package1/Ap
p2
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.


so how to run the App2 class?

Answer

You should compile using the -d option so that the classes end up in an appropriate directory hierarchy:

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

Also, you shouldn't use a package name starting with java in the first place.

Also, if you put the source in an appropriate directory hierarchy, and compile/run from the root of the hierarchy, you wouldn't have this problem.

Comments