Is it by spec that, given a MyClass.java file containing
package com.mycorp.foo;
public class MyClass {
public static void main (String[] args) {
System.out.println("Hello, world!");
}
}
in the following path (note the dot in the folder name):
./com/mycorp.foo/MyClass.java
the following works fine:
$ javac com/mycorp.foo/MyClass.java
producing ./com/mycorp.foo/MyClass.class while this doesn’t work:
$ java com.mycorp.foo.MyClass
Exception in thread "main" java.lang.NoClassDefFoundError: com/mycorp/foo/MyClass
Caused by: java.lang.ClassNotFoundException: com.mycorp.foo.MyClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The packaging structure mentioned at the top of the class file has less to do with compilation and more to do with Runtime class loading.
You can put any packagename and compile it. e.g. following java class compiles
It compiles even if you don’t put inside a folder structure same as package declaration. You can test it by not putting in any folder (e.g
java Test.java)2 . Packages organization is more important while class loading. The classloader will always search for the class into the folder based on package structure. So when you are trying to run your program, the classloader tries to search for the class file in a folder as per the package structure.