且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 11 中生成代码,但针对 Java 8 及更高版本?

更新时间:2023-08-22 20:22:52

虽然理论上可以使用复杂的工具将为 JDK 11 编译的类转换为 JDK 8,但这并非易事.二进制级别有显着变化.

While conversion of classes compiled for JDK 11 to JDK 8 would be theoretically possible with a sophisticated tool, it’s not trivial. There are significant changes on the binary level.

首先,JDK 11 引入了 nest 类型,在访问内部/外部类的 private 成员时无需生成合成访问器方法.当然,这种访问在旧版本中会失败.

First, JDK 11 introduced nest types, which eliminates the need to generate synthetic accessor methods when accessing private members of inner/outer classes. Of course, such access would fail in older versions.

它还引入了动态常量,但我不知道 Java 语言是否在任何地方利用了该特性.这主要用于未来的版本.

It also introduced dynamic constants, though I don’t know whether the Java language exploits that feature anywhere. This is mainly intended for future versions.

然后,从 JDK 9 开始,字符串连接使用 invokedynamic 编译,参考 java.lang.invoke.StringConcatFactory 在 Java 8 中不存在.

Then, since JDK 9, string concatenation gets compiled using invokedynamic referring to java.lang.invoke.StringConcatFactory which is not present in Java 8.

一个可以工作的特性是接口中的私有方法,在 Java 9 中作为语言特性引入,但在 Java 8 中已经在二进制级别处理.

A feature that could work, is private methods in interfaces, introduced in Java 9 as a language feature, but already handled on the binary level in Java 8.

Java 8 也无法处理模块定义,但我想,它们会被忽略.

Java 8 would also be unable to process module definitions, but I suppose, they would be ignored.