Is there a way to make a Java class public but only public with a JAR file? AKA, it's not package private, instead it's package public, but it's not JAR public?
Say I have a structure like this:
project/
package1/
One.java
package2/
Two.java
package3/
Three.java
Since the 3 .java files are in different packages, I need to make things public. But is there a way to make them only public to the JAR that will contain the project? Such that if another project imports the JAR, it can't see certain public classes/field?
No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier).
Yes, but since it is a library this class will be available in it too.
Using project Jigsaw in Java 9 you can do exactly that where you can decide on the packages you want to export. For example:
module com.yourproject {
exports com.yourproject.package1;
}
This will make sure that only package1
is exported.
Pointed already by existing answers, the way to adapt to this is modularising your code (adding a module declaration with module-info.java
for a start). Just detailing them out with reference to sotms#module-declaration
exports
clauses can be added to declare that the module makes all, and only, thepublic
types in specific packages available for use by other modules:
module com.foo.bar {
requires org.baz.qux;
exports com.foo.bar.alpha;
exports com.foo.bar.beta;
}
If a module’s declaration contains no exports clauses then it will not export any types at all to any other modules.
and from the JLS section Exported and Opened packages
The
exports
directive specifies the name of a package to be exported by the current module. For code in other modules, this grants access at compile time and run time to thepublic
andprotected
types in the package, and thepublic
andprotected
members of those types (§6.6). It also grants reflective access to those types and members for code in other modules.
and further related to qualified and unqualified exports...
For a qualified directive, the public and protected types in the package, and their public and protected members, are accessible solely to code in the modules specified in the to clause. The modules specified in the
to
clause are referred to as friends of the current module. For an unqualified directive, these types and their members are accessible to code in any module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With