You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code的settings.json中启用JDK 20预览特性?配置后仍报错

问题:VS Code中启用JDK 20预览特性仍报错

我已经修改了VS Code的settings.json(路径:~/Library/Application Support/Code/User/settings.json)来启用JDK 20的预览特性,配置如下:

{
    "java.configuration.runtimes": [
        {
          "name": "JavaSE-20",
          "path": "/Users/rahulraj/Library/Java/JavaVirtualMachines/openjdk-20.0.1/Contents/Home",
          "default": true,
          "vmargs": [ "--enable-preview" ]
        }
    ]
}

但运行虚拟线程代码时,依然抛出如下错误:

Exception in thread "main" java.lang.UnsupportedOperationException: Preview Features not enabled, need to run with --enable-preview
        at java.base/jdk.internal.misc.PreviewFeatures.ensureEnabled(PreviewFeatures.java:49)
        at java.base/java.lang.Thread.ofVirtual(Thread.java:859)
        at Test.main(Test.java:21)

我的launch.json配置如下:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "Current File",
            "request": "launch",
            "mainClass": "${file}"
        },
        {
            "type": "java",
            "name": "App",
            "request": "launch",
            "mainClass": "App",
            "projectName": "VirtualThread_c7b22327",
            "args": ["--enable-preview"]
        }
    ]
}

我确认settings.json的配置和JDK路径都正确,但找不到问题所在。


解决方法

问题出在两处:

  1. settings.json中的vmargs是配置给VS Code的Java语言服务器使用的,不会作用于程序运行时的JVM。
  2. launch.json里的args字段是传递给Java程序的应用参数,而非JVM启动参数。要配置JVM参数,需要用vmArgs字段(注意大小写)。

修改你的launch.json,给每个需要启用预览特性的配置添加vmArgs:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "Current File",
            "request": "launch",
            "mainClass": "${file}",
            "vmArgs": "--enable-preview"
        },
        {
            "type": "java",
            "name": "App",
            "request": "launch",
            "mainClass": "App",
            "projectName": "VirtualThread_c7b22327",
            "vmArgs": "--enable-preview"
        }
    ]
}

另外,编译代码时也需要启用预览特性,你可以在settings.json中添加编译参数:

{
    "java.configuration.runtimes": [
        // 原有运行时配置...
    ],
    "java.compilerArgs": ["--enable-preview"]
}

修改后重启VS Code,再运行虚拟线程代码即可正常执行。

内容的提问来源于stack exchange,提问作者Rahul Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:02:21