Class resides in different directory than what the package specifies - how come?
The following statements seem to disturbingly function:
robert@neghvar:~/tmp> cat org/foo/Bar.java
public class Bar {
}
robert@neghvar:~/tmp> javac org/foo/Bar.java
robert@neghvar:~/tmp> javap org.foo.Bar
Compiled from "Bar.java"
public class org.something.Bar extends java.lang.Object{
public org.something.Bar();
}
Although the Bar class file is in the org/foo
directory and declares the org.something
package, the compiler does not complain. I was under the impression that java mandated a directory hierarchy which follows the package name. Was I mistaken? If so, what are the consequenc开发者_StackOverflow中文版es of mixing up package names?
The source directory structure is not required to follow package naming (even though it almost always does by convention.)
I think the Sun/Oracle javac,javap,java,etc. tools (and all other Java implementations that I know of) are what mandate the subdirectory per package name component rule (along with the default class loaders). I couldn't find anything authoritative, but it doesn't seem to be a requirement of the Java language specification:
- http://java.sun.com/docs/books/jls/third_edition/html/packages.html
It's purely convention. The compiler will use the package names.
Having said that, it's not usually a good idea to break with this convention. It'll cause inconsistency (the classes generated will be in directories following the package) and some confusion!
精彩评论