Java package folders with a dot in the name

前端 未结 2 939
臣服心动
臣服心动 2021-01-21 01:37

Is it by spec that, given a MyClass.java file containing

package com.mycorp.foo;

public class MyClass {
  public static void main (String[] args) {         


        
相关标签:
2条回答
  • 2021-01-21 02:02

    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.

    0 讨论(0)
  • 2021-01-21 02:02

    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.

    0 讨论(0)
提交回复
热议问题