本文主要研究下java9 opens与exports的区别
包括public及private类型
)
但是编译时期,仅仅允许该module中声明过exports的包可以访问,如果没有exports则该包的类在编译时期不可读表示允许在编译时和运行时访问指定包的public成员
编译报错
)
Exception in thread "main" java.lang.IllegalAccessException: class com.packt.App (in module packt.main) cannot access class com.packt.lib.sub1.Sub1Service (in module packt.lib) because module packt.lib does not export com.packt.lib.sub1 to module packt.main at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361) at java.base/jdk.internal.reflect.Reflection.ensureMemberAccess(Reflection.java:107) at java.base/java.lang.Class.newInstance(Class.java:553) at packt.main/com.packt.App.main(App.java:25)newInstance运行时报错
)
Exception in thread "main" java.lang.IllegalAccessException: class com.packt.App (in module packt.main) cannot access class com.packt.lib.sub1.Sub1Service (in module packt.lib) because module packt.lib does not export com.packt.lib.sub1 to module packt.main at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361) at java.base/jdk.internal.reflect.Reflection.ensureMemberAccess(Reflection.java:107) at java.base/java.lang.Class.newInstance(Class.java:553) at packt.main/com.packt.App.main(App.java:26)module packt.lib {
exports com.packt.lib;
exports com.packt.lib.sub1;
}
open module packt.lib {
exports com.packt.lib;
exports com.packt.lib.sub1;
}
两种访问方式的反射均正常编译及运行。
包括public及private类型
);opens package的作用只是允许该包在runtime都允许deep reflectionopen及opens都仅仅是开放runtime时期的可以通过反射访问(
蕴含了运行时的exports
)。
编译及运行时
)如果反射不直接通过类名调用,只是运行时通过包名使用,则只需open或opens即可
如果是通过类名来反射,由于用到了该类,需要通过exports指定可以访问,不指定则编译期立即报错
如果是通过类名来反射使用public方法或newInstance,如果没有exports,则运行时报错
如果有exports,但是没有open,由于默认—illegal-access=permit,因此相当于带上了open