Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make classes public, but remain private to a JAR file

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?

like image 492
Alexander Mills Avatar asked Feb 11 '19 09:02

Alexander Mills


People also ask

Can we keep class as private in Java?

No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier).

Can I create a jar without main class?

Yes, but since it is a library this class will be available in it too.


2 Answers

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.

like image 170
Sleiman Jneidi Avatar answered Sep 22 '22 09:09

Sleiman Jneidi


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, the public 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 the public and protected types in the package, and the public and protected 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.

like image 35
Naman Avatar answered Sep 23 '22 09:09

Naman