IntelliJ指示尽管使用Java 14,增强型开关块仍无法工作

问题描述

我正在尝试使用Java 14中标准化的增强型开关块。旧版本是这样:

switch (expression) {
    case OPTION1:
        foo();
        break;
    case OPTION2:
        bar();
        break;
}

但是自从我使用Java 14以来,我应该可以使用它:

switch (expression) {
    case OPTION1 -> foo();
    case OPTION2 -> bar();
}

这是MRE:

public class Main {
    public static void main(String[] args) {
        String demo = Math.random() > 0.5 ? "Hello": "World";
        switch (demo) {
            case "Hello" -> System.out.println("The string contained Hello");
            case "World" -> System.out.println("The string contained World");
        }
    }
}

The code in my IDE

当我编写该代码时,IntelliJ会给我以下警告:

Enhanced 'switch' blocks are not supported at language level '14'

语言级别'14'不支持增强的'switch'块

但是,该警告尽管以红色突出显示以指示编译时错误,但还是不正确的。代码正确编译,并且switch块按预期工作,因为我使用的是Java14。为什么会收到此警告?

编辑:每个请求的项目结构

Project structure

编辑:我的iml文件

<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="module-library">
      <library>
        <CLASSES>
          <root url="jar://$USER_HOME$/Downloads/MathParser.org-mXparser-v.4.4.0/MathParser.org-mXparser-v.4.4.0/bin/jdk13/MathParser.org-mXparser-v.4.4.0-jdk13.jar!/" />
        </CLASSES>
        <JAVADOC />
        <SOURCES />
      </library>
    </orderEntry>
  </component>
</module>

解决方法

首次使用intellij 2020

通常的原因是sdk,jdk和语言级别未对齐,

在“项目结构”的“项目”选项卡中检查“项目”和“模块”是否一致,请参见下文(确定,我使用的是11级语言)

enter image description here enter image description here

项目显示openjdk-14 enter image description here

插入插入的java14.iml文件内容

<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_14" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src/com" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>
,

我已经尝试过了,并且工作正常,我想您可能会忘记添加软件包名称

package com.company;

public class Main
{
    public static void main(String[] args) {
        
        String demo = Math.random() > 0.5 ? "Hello": "World";
        switch (demo)
        {
            case "Hello" -> System.out.println("The string contained Hello");
            case "World" -> System.out.println("The string contained World");
        }
    }
}

这是我的项目结构的屏幕截图,请尝试将其与您的项目进行比较

enter image description here