近期在用 JDK 11 写一个项目,经常遇到睡醒一觉发现项目不能正常编译的情况,报错诸如「不再支持源选项 5 请使用 6 或更高版本」、「Method references are allowed only at source level 1.8 or above」等等。每次都要慢慢排错很麻烦,故将排错流程总结于此,方便日后查看。

本文有可能会因为我踩了什么新坑而不定时更新。

可选操作(亲测没有影响,但许多教程提到这种做法):在 pom.xml 中添加以下两段代码中的任意一段。

1
2
3
4
5
6
7
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
1
2
3
4
5
6
7
8
9
10
11
12
13
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11.0</source>
<target>11.0</target>
</configuration>
</plugin>
</plugins>
</build>

其他有用的操作:点击 File - Settings。

file-settings

找到 Java Compiler,将 Project bytecode version 和 Target bytecode version 改为 11 后,点击 OK 保存。

settings-java-compiler

点击 File - Project Structure。

file-project-structure

将 Project 中的能改成 11 的都改成 11。

project-structure-project

Modules 中的 Sources 和 Dependencies 同理。

modules-sources

modules-dependencies

正常到这里就应该可以正常编译运行了,如果还不行的话,可以检查项目下的 .settings/org.eclipse.jdt.core.prefs 文件。

1
2
3
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.source=11

学到了的兄弟们把「👴杀了IDEA的🐴」打在公屏上。