How to make a Java class accessable within the same library only (in Java 8)

This is an excellent use-case for Java 9's module system. With it, you can export all packages except for com.test.pac4, prohibiting any project that depends on your library from accessing any classes within that package (unless your users override it via --add-exports).

To do this, you can create a module-info.java file in your source directory that contains the following (I recommend changing the module name):

module com.test.project {
    exports com.test.pac1;
    exports com.test.pac2;
    exports com.test.pac3;
}

You'll also need to use requires for any modules that your project depends on (see: Java 9 Modularity).


If you're using Java 8 or below, then the above solution isn't possible, as the module system was introduced in Java 9.

One workaround on Java 8 is to modify your project hierarchy; you can move every class that accesses CommonClass into a single package, and then make CommonClass package-private. This will prevent your library's users from being able to access CommonClass.

Tags:

Java