Make classes public, but remain private to a JAR file
Asked Answered
P

3

7

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?

Pimp answered 11/2, 2019 at 9:40 Comment(1)
Yes. A module, introduced in Java 9. Or move the files to the same package.Chalcanthite
T
8

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.

Terylene answered 11/2, 2019 at 9:49 Comment(0)
B
3

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.

Botel answered 11/2, 2019 at 10:56 Comment(2)
so you just throw this module.java file there somewhere? could you perhaps show how thr structure might look?Pimp
@AlexanderMills here is an official quick start guide for that. You keep that file at the project level in the hierarchy.Botel
L
2

Yes, Java 9 introduced modules which are designed to solve this kind of problem.

Lareelareena answered 11/2, 2019 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.