简体   繁体   中英

Java package access is strange. Is this intended?

I did a experiment where i extended a java.lang package class and couldn't access the package methods or field (methods or fields with no public or protected). Ok.

Then i put in my extension in a 'java.lang' on my source root and tried again and it compiled. So package access restriction is only cosmetic (you need to put it in the same place as the other classes, and thus the user will find it by importing java.lang) and they actually might as well be public, since there is no actual weaker level of access here? (protected at least assures that it's a extension overriding).

If you put your code into a package called java.lang, it means your code belongs to that package, so you can indeed access the "package" methods described in the original java.lang.

Just think about this: in a project you have "package" access level methods and you want to unit test them. You can do this in classes in the same package, meaning exactly in the same directory or you can have 2 separate directories: src and test, with the same package naming. This way the unit tests can be defined in the same package as the code, but they are located in a different location on disk.

The concept of package exists in Java to provide an additional level of granularity in the accessibility of class members. Due to flexibility of the class loading mechanism in Java, their is nothing to restrain you to access package-level members and attributes of a class C when you declare your own classes in the same package as this class C.

Some specifications enforce more restrictive access policies like OSGI. OSGI comes with the additional concept of bundle , absent from the Java language itself. Bundles are a set of classes packaged in a single jar. They declare in a manifest file which classes and which packages they export , which other bundles can access. Those packages and classes which are not exported are strictly not accessible from other bundles.

What is more, you cannot access package-level methods and attributes of a class C of a bundle from another bundle, even though class C is exported. An OSGI class loader will not allow you to load a class from a package which is already "owned" by another bundle.

If you are interested in these questions around accessibility and packaging, have a look at the Jigsaw project , which intends to redesign the modularity in Java and should come in next release of Java SE (Java SE 8, though I am not sure it has not been postponed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM