如何在IntelliJ中为Maven/Gradle项目配置使用Preview/Incubating API
在IntelliJ中启用Java Preview/Incubating API的配置指南
作为OpenJDK开发流程的一部分,Java会将部分在研新功能以Preview API或Incubating API的预发布形式推出,比如虚拟线程(预览版)、结构化并发(孵化版)这类功能。如果要在IntelliJ的Maven或Gradle项目中试用这些功能,需要完成以下配置:
一、Maven项目配置
在项目的pom.xml中添加或修改以下配置:
- 指定支持目标API的JDK版本(例如虚拟线程需要JDK 19及以上)
<properties> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> </properties>
- 配置编译与运行参数,启用Preview/Incubating API
<build> <plugins> <!-- 编译插件配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <!-- 启用Preview API --> <compilerArgs>--enable-preview</compilerArgs> <!-- 若使用Incubating API,需添加对应模块,比如结构化并发的jdk.incubator.concurrent --> <compilerArgs>--add-modules=jdk.incubator.concurrent</compilerArgs> </configuration> </plugin> <!-- 运行插件配置 --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <configuration> <executable>java</executable> <arguments> <argument>--enable-preview</argument> <argument>--add-modules=jdk.incubator.concurrent</argument> <argument>-classpath</argument> <classpath/> <argument>你的主类全路径</argument> </arguments> </configuration> </plugin> </plugins> </build>
二、Gradle项目配置
根据使用的DSL语法,修改项目的build.gradle或build.gradle.kts:
Groovy DSL
plugins { id 'java' } java { sourceCompatibility = JavaVersion.VERSION_19 targetCompatibility = JavaVersion.VERSION_19 } // 编译任务配置 tasks.withType(JavaCompile) { options.compilerArgs += ['--enable-preview', '--add-modules=jdk.incubator.concurrent'] } // 测试任务配置 tasks.withType(Test) { jvmArgs += ['--enable-preview', '--add-modules=jdk.incubator.concurrent'] } // 运行任务配置 tasks.withType(JavaExec) { jvmArgs += ['--enable-preview', '--add-modules=jdk.incubator.concurrent'] }
Kotlin DSL
plugins { java } java { sourceCompatibility = JavaVersion.VERSION_19 targetCompatibility = JavaVersion.VERSION_19 } tasks.withType<JavaCompile> { options.compilerArgs.addAll(listOf("--enable-preview", "--add-modules=jdk.incubator.concurrent")) } tasks.withType<Test> { jvmArgs.addAll(listOf("--enable-preview", "--add-modules=jdk.incubator.concurrent")) } tasks.withType<JavaExec> { jvmArgs.addAll(listOf("--enable-preview", "--add-modules=jdk.incubator.concurrent")) }
三、IntelliJ IDE配置
- 配置项目JDK与语言级别
- 打开
File > Project Structure(快捷键:Ctrl+Alt+Shift+S) - 在
Project Settings > Project中,将Project SDK和Project language level设置为对应JDK版本,并选择X - Preview features enabled(例如19 - Preview features enabled)
- 打开
- 配置运行/调试参数
- 打开
Run > Edit Configurations - 在目标运行配置的
VM options中添加:--enable-preview(若使用Incubating API,需额外添加--add-modules=jdk.incubator.concurrent这类模块参数)
- 打开
- 调整预览API检查提示(可选)
- 打开
File > Settings > Editor > Inspections - 在
Java > Compiler issues下找到Preview feature,将检查级别改为Warning或None,减少IDE提示干扰
- 打开
内容的提问来源于stack exchange,提问作者Basil Bourque
相关产品推荐
相关产品推荐

