Why Java 9 does not simply turn all JARs on the class path into automatic modules?

强颜欢笑 提交于 2020-01-01 00:48:10

问题


In order to understand the categories we have:

  • platform explicit modules
  • application explicit modules
  • open modules
  • automatic modules
  • unnamed module

All classes and jars within the classpath will be part of the unnamed module. But why is that what we need? Where is the advantage over automatic modules? I could "require" those damn legacy jars to make them to an automatic module. Do I not have included everything with it?


回答1:


There are at least two reasons:

  • Just as regular modules, automatic ones are suspect to certain examinations by the module system, e.g. not splitting packages. Since JARs on the class path can (and occasionally do) split packages, imposing that check on them would be backwards-incompatible and break a number of applications.
  • The unnamed module can read all platform modules, whereas automatic modules can only read those that made it into the module graph. That means a JAR needing the java.desktop module (for example) will work from the class path but not from the module graph unless java.desktop also makes it into the graph (via a dependency or --add-modules).

I have no time right now to check the second but that's what the State of the Module system says:

After a module graph is resolved, therefore, an automatic module is made to read every other named module, whether automatic or explicit

Resolution works on the declared dependencies and an automatic modules declares none.




回答2:


Apart from the items listed in the accepted answer, there is one more difference: unnamed modules can access all packages of modules that come with Java, even is they are not exported. As long the class is public, access will work - the same as before Java 9. But as soon as a jar is run from module path, it will be able to access only exported packages.

For example if some .jar has this code:

com.sun.jmx.remote.internal.ArrayQueue c = new com.sun.jmx.remote.internal.ArrayQueue(10);

it will run normally without any warnings when placed on class path, but when run from module path (as automatic module) it will fail at runtime:

Exception in thread "main" java.lang.IllegalAccessError: class test1.C 
(in module test1) cannot access class com.sun.jmx.remote.internal.ArrayQueue 
(in module java.management) because module java.management does not export 
com.sun.jmx.remote.internal to module test1

Note that this is different from the well known illegal reflective access warning, which is about using reflection to access private fields or methods. Here we are statically (non-reflectively) accessing public class (but from non-exported package).



来源:https://stackoverflow.com/questions/45166921/why-java-9-does-not-simply-turn-all-jars-on-the-class-path-into-automatic-module

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