Java 9 overlapping non-exported packages

独自空忆成欢 提交于 2019-12-21 02:04:15

问题


Various resources (infoq, jigsaw-dev, osdir) indicate that having the same package in different java modules will lead to a LayerInstantiationException, even when the packages are internal to the module (non-exported).
This seems to be the exact opposite of what the requirements say :

The Java compiler, virtual machine, and run-time system must ensure that modules that contain packages of the same name do not interfere with each other. If two distinct modules contain packages of the same name then, from the perspective of each module, all of the types and members in that package are defined only by that module.

So are (will) two modules used by an app be able to contain private packages of the same name ?

EDIT
This is an issue of JMPS as pointed by Stanislav Lukyanov


回答1:


As said in the discussions you've linked, the issue is about mapping between class loaders and modules.

When you're loading two modules M1 and M2 both containing a non-exported (a.k.a. concealed) package P via a class loader CL JPMS has to reject such configuration, since otherwise both key JPMS principles - strong encapsulation and reliable configuration - could be broken. By throwing an exception here JPMS actually implements the requirement you've quoted and ensures that no conflicts may break anything later during the execution.

On the other hand, when you're loading M1 and M2 via two loaders CL1 and CL2 you're actually creating two run-time packages {CL1, P} and {CL2, P}, so there is no collision and the Layer can be instantiated.

The usability problem here is that java uses single loader for all modules of the application layer (the "starting" one, created from the command-line arguments) which leads to the LayerInstantiationException. That's currently an open issue on the JPMS list, see [here] (http://openjdk.java.net/projects/jigsaw/spec/issues/#AvoidConcealedPackageConflicts). But regardless of the issue's resolution, if needed, you should be able to deal with the split packages by writing a tiny main class that will create the Configuration you need (BTW a JPMS-aware application container will probably do it for you).




回答2:


This definition is open to interpretation. It remains correct as Jigsaw ensures that two modules never define shared packages by crashing the class loading in case of such a conflict.

If you look into Java 9's class loader implementation, you can see that a package name is mapped by to a single module. Its therefore impossible two have two modules to declare ownership. It is however possible that two class loaders in child-parent relationship define the same package.



来源:https://stackoverflow.com/questions/40616739/java-9-overlapping-non-exported-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!