Java package folders with a dot in the name

 ̄綄美尐妖づ 提交于 2021-02-05 05:50:06

问题


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)

回答1:


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.

  1. You can put any packagename and compile it. e.g. following java class compiles

    package com.sa.test.me.yes.no;
    
     public class Test{
    
     public static void main(String[] args){
    
     System.out.println("Hello");
     }
    
      }
    

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.




回答2:


The Oracle documentation points to the fact the source tree does not have to match the object files tree. javac lets anything go for that very reason, but java will require the directory structure to follow the standard of having one subdirectory per element of the dot-separated package name.



来源:https://stackoverflow.com/questions/10719306/java-package-folders-with-a-dot-in-the-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!