JDK 21预览功能详解:解决--enable-preview编译错误

本文详细介绍了JDK 21中的预览功能使用,包括如何解决"--enable-preview must be used with either -source or --release"编译错误,以及String Templates等新特性的实际应用示例和完整JEP功能列表。

error: –enable-preview must be used with either -source or –release

JDK 21版本正在稳步推进,预计将在9月19日左右发布,目前还不是正式版。更重要的是,它提供了预览功能。

是时候下载其中一个版本并进行尝试了。实际上我在几周前已经尝试过,所以已经安装了它。

例如:

1
2
3
openjdk version "21-ea" 2023-09-19
OpenJDK Runtime Environment (build 21-ea+26-2328)
OpenJDK 64-Bit Server VM (build 21-ea+26-2328, mixed mode, sharing)

有趣的是,有几个非常酷的功能仍然处于预览状态。例如,我尝试使用InfoQ博客中提到的StringTemplates:

1
2
3
4
5
6
~/git/java-examples 🐠  javac StringTemplates.java                                               14:50
StringTemplates.java:6: error: string templates are a preview feature and are disabled by default.
    public static String html = STR."""
                                    ^
  (use --enable-preview to enable string templates)
1 error

要启用功能进行编译,请使用以下示例命令:

1
javac StringTemplates.java --enable-preview --release 21

最后,在运行时也需要启用预览功能:

1
2
3
4
5
6
7
8
9
~/git/java-examples 🐠  java --enable-preview StringTemplates                                    14:56
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <p>Hello, world</p>
  </body>
</html>

Java 21中包含的JEP列表:

JEP 标题
430 String Templates (Preview)
431 Sequenced Collections
439 Generational ZGC
440 Record Patterns
441 Pattern Matching for switch
442 Foreign Function & Memory API (Third Preview)
443 Unnamed Patterns and Variables (Preview)
444 Virtual Threads
445 Unnamed Classes and Instance Main Methods (Preview)
446 Scoped Values (Preview)
448 Vector API (Sixth Incubator)
449 Deprecate the Windows 32-bit x86 Port for Removal
451 Prepare to Disallow the Dynamic Loading of Agents
452 Key Encapsulation Mechanism API
453 Structured Concurrency (Preview)
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计