Package structure should be same as directory structure in Java “always”?

♀尐吖头ヾ 提交于 2020-01-13 16:31:04

问题


Package structure should be same as directory structure in Java it seems in Eclipse. I tried to browse through the formal documentation on Oracle Java docs but nowhere I could find this rule

Does this rule extend to other IDEs such as Netbeans or is this a rule of Java language itself? How strict is this rule, can it be deviated from and why was it made?


回答1:


It's specified in the JLS as a rule that compilers may require:

Packages that are stored in a file system may have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily.

For example, if you specify all the source filenames on the command line for javac, you don't have to follow those rules... but it's pretty much universally used, and I wouldn't dream of violating this rule for anything other than tiny tests.

Note that by default, javac will generate the class file as a peer of the source file, regardless of package structure; if you specify -d it will generate the appropriate output structure even if it doesn't match the source structure.




回答2:


Maybe you need to have a look at a good tutorial about packages. The first sentence of the link:

Many implementations of the Java platform rely on hierarchical file systems to manage source and class files, although The Java Language Specification does not require this.




回答3:


Its not a IDE specific. Directory structure and package structure should match each other. You can find more details in Java Specification and Certification books.




回答4:


Not really. You can have following code, without putting it inside my/app folder

package my.app;

public class Tmp{

}

and compile this without errors from command prompt.

But for running the application, the class files needs to be in respect folders mentioned in package.

As Jon Skeet mentions its more for organization purposes so that run time can resolve if there are conflicting class names.



来源:https://stackoverflow.com/questions/9416017/package-structure-should-be-same-as-directory-structure-in-java-always

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