Is there any way that users of my modular library are able to access classes which have not been exported?

gjvatsalya :

I'm trying to get familiar with the module system introduced in Java 9, and I would like to know the best way to leverage it.

For a library I'm writing, I would like to do the following (ignore the naming of the packages):

  • Expose only interfaces, simple POJO classes, and factory classes via com.myproject.api. Everything in this class can be used by the users.
  • Put the implementation of interfaces in com.myproject.core. Users should not be able to access anything in here.

My reasoning is that users do not need to get confused or overwhelmed by the implementation logic. Instead, they can just look at (hopefully) clean and well documentated interfaces.

However, due to the way Java packages work, it can be difficult to restrict use of certain classes without making them all package private. But I don't like putting all the classes in one package, and would rather organize them into various packages.

After reading about the module system, I believe I can do the following to achieve what I want. This is the module-info.java file:

module com.myproject {
    exports com.myproject.api;
}  

From my understanding, the users of my library will be able to use everything defined in the com.myproject.api package (by using require com.mypojrect.api in their own module-info file).

But is there any way that users will be able to access anything in the com.myproject.core package? I have no problem with them looking at the code (via IDE or the source code itself), but I just don't want to end up supporting classes/methods/logic which I didn't want to expose.

I'm concerned that users who don't have a modularized application or users who put my library JAR on the classpath will somehow find a way to get access to the supposed restricted package.

Please let me know if you need any other information.

LppEdd :

A pre-JDK9 user of your library cannot exist, as you're going to use the Java Platform Module System, which is post-JDK8, and thus you're going to compile to a class version greater than 52.

Said that, your users will be able to look at the source code (if shipped), and obviously they will be able to extract your .class files.


By definition

a type in a module is not accessible to other modules unless it’s a public type and you export its package.

The only way to gain Reflective access to your classes would be if you willingly opened them, with the

opens your.package

directive. So basically, you're covered also on the Reflection aspect.
And the opens directive exposes to Reflection only public definitions.


If you want to control Reflective access to your classes in a non-modular/pre-JDK9 environment, SecurityManager might be what you're looking for. However this requires access to the JVM configuration.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116855&siteId=1