Java 9 中的 --add-exports 和 --add-opens 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44056405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:54:28  来源:igfitidea点击:

What's the difference between --add-exports and --add-opens in Java 9?

javacommand-line-argumentsjava-9jigsawjava-module

提问by vip

Java 9 (jdk-9+170) does not allow by default an application to see all classes from the JDK, unlike all previous versions of Java, due to the new module system.

由于新的模块系统,Java 9 (jdk-9+170) 在默认情况下不允许应用程序查看 JDK 中的所有类,这与所有以前版本的 Java 不同。

To workaround this, the javacommand line offers a new argument --add-exportswhich allows to break encapsulation as follows:

为了解决这个问题,java命令行提供了一个新参数--add-exports,它允许按如下方式破坏封装:

java -jar josm.jar --add-exports java.base/sun.security.util=ALL-UNNAMED --add-exports java.base/sun.security.x509=ALL-UNNAMED

java -jar josm.jar --add-exports java.base/sun.security.util=ALL-UNNAMED --add-exports java.base/sun.security.x509=ALL-UNNAMED

This is well explained in JEP 261.

这在JEP 261 中有很好的解释。

I have read about a similar option --add-opensusing the same syntax, but the JEP 261 has not yet been updated to describe it (last update: 2017/03/08 13:58).

我已经阅读了--add-opens使用相同语法的类似选项,但 JEP 261 尚未更新以对其进行描述(最后更新:2017/03/08 13:58)。

What is the difference between these two options?

这两个选项有什么区别?

EDIT: The JEP 261has been updated on 2017-09-22 to explain it.

编辑JEP 261已于 2017-09-22 更新以对其进行解释。

回答by Nicolai

  • With --add-exportsthe package is exported, meaning all public types and members therein are accessible at compile and run time.
  • With --add-opensthe package is opened, meaning all types and members (not only public ones!) therein are accessible at run time.
  • 随着--add-exports包被导出,这意味着在编译和运行时可以访问其中的所有公共类型和成员。
  • 随着--add-opens包装被打开,这意味着所有类型和成员(不仅是公立!)其中是在运行时使用。

So the main difference at run time is that --add-opensallows "deep reflection", meaning access of non-public members. You can typically identify this kind of access by the reflecting code making calls to setAccessible(true).

所以运行时的主要区别是--add-opens允许“深度反射”,即非公共成员的访问。您通常可以通过调用 的反射代码来识别这种访问setAccessible(true)