jdk17 体验

作为LTS版本的java17 一定是未来,考虑将dawdler-series做一个java17的版本。所以需要先踩一下坑。

以下是一些新特性

306: Restore Always-Strict Floating-Point Semantics
356: Enhanced Pseudo-Random Number Generators
382: New macOS Rendering Pipeline
391: macOS/AArch64 Port
398: Deprecate the Applet API for Removal
403: Strongly Encapsulate JDK Internals
406: Pattern Matching for switch (Preview)
407: Remove RMI Activation
409: Sealed Classes
410: Remove the Experimental AOT and JIT Compiler
411: Deprecate the Security Manager for Removal
412: Foreign Function & Memory API (Incubator)
414: Vector API (Second Incubator)
415: Context-Specific Deserialization Filters

除了ZGC与JPMS其他无喜感,基本不关注。

本文记录 JPMS使用过程。

自行了解下 module-info.java
 
以下为代码实例
 
module-info.java
module unsafe {
requires java.base;
requires jdk.unsupported;
}
Test.java
package unsafe;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
System.out.println("hello");
Class c = Class.forName("jdk.internal.misc.Unsafe");
System.out.println(c);
Method method = c.getMethod("getUnsafe", null);
method.setAccessible(true);
System.out.println(method.invoke(null, null));

}
}
以上代码很简单只是为了试验是否可以使用jdk.internal.misc.Unsafe.
 
因为 java17 jdk.internal.misc.Unsafe 在 java.base中并未exports,所以以上代码无法执行会报错。
 
 
各种玩法:
 
第一种 直接编译 javac
 
javac unsafe/Test.java
 
[srchen @bogon src]$ java unsafe.Test
hello
class jdk.internal.misc.Unsafe
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make public static jdk.internal.misc.Unsafe jdk.internal.misc.Unsafe.getUnsafe() accessible: module java.base does not "exports jdk.internal.misc" to unnamed module @5f8754e
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:199)
at java.base/java.lang.reflect.Method.setAccessible(Method.java:193)
at unsafe.Test.main(Test.java:13)
 
报错...
 
采用 --add-opens 运行试试
[srchen @bogon src]$ java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED unsafe.Test
hello
class jdk.internal.misc.Unsafe
jdk.internal.misc.Unsafe@4d7e1886
 
可以运行
 
 
模块方式
 
编译
javac mods/unsafe module-info.java unsafe/*.java
 
另一种
 
javac --add-exports java.base/jdk.internal.misc=unsafe -d mods/unsafe module-info.java unsafe/*.java
 
--add-exports一般用于ide
 
运行
[srchen @bogon src]$ java --module-path mods --add-opens=java.base/jdk.internal.misc=unsafe --module unsafe/unsafe.Test
hello
class jdk.internal.misc.Unsafe
jdk.internal.misc.Unsafe@77459877
{{o.name}}
{{m.name}}

猜你喜欢

转载自my.oschina.net/u/3861980/blog/5376032