JDK 21 预览功能编译错误解析:--enable-preview 必须与 -source 或 --release 搭配使用

本文详细介绍了在JDK 21中使用预览功能时遇到的编译错误及解决方法,包括String Templates等预览特性的启用方式,以及Java 21中包含的主要JEP特性列表。

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

JDK 21版本正在积极开发中,预计将于9月19日左右发布,目前尚未达到通用可用(GA)状态。该版本提供了多项预览功能。

我下载了其中一个发布版本进行尝试。实际上几周前我已经尝试过,所以已经安装了该版本。

例如:

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 设计