The class is in different directories than indicated in the package - how does this happen?

The following statements seem to be violated:

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 got the impression that java required a directory hierarchy that follows the package name. I was wrong? If so, what are the consequences of mixing package names?

+4
source share
2 answers

This is a pure convention. The compiler will use package names.

Having said that, it is generally not advisable to violate this convention. This will cause inconsistency (the generated classes will be in the directories after the package) and some confusion!

+2
source

The structure of the source directory is not required to indicate the name of the package (although this is almost always done by convention).

I think Java / Java, javap, java, etc. tools (and all the other Java implementations that I know of) are that the subdirectory is mandated for one of the composite rules for the package name (along with the default class loaders). I could not find anything authoritative, but it seems that this is not a requirement of the Java language specification:

+3
source

Source: https://habr.com/ru/post/1337220/


All Articles