使用高版本JDK编译低版本代码

背景

SonarQube运行于Java17,使用Sonar的Maven插件编译时,如果编译使用的JDK版本低于SonarQube使用的Java17,则会提示Java文件不匹配问题。

Error during SonarScanner execution
java.lang.UnsupportedClassVersionError: org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0

maven-compiler-plugin

通过设置编译插件配置来输出指定版本的编译。

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><fork>true</fork><source>1.8</source><compilerVersion>1.8</compilerVersion><target>1.8</target><encoding>UTF-8</encoding></configuration>
</plugin>

当缺少上面的configuration配置时,可能出现编译报错。

Fatal error compiling: java.lang.ExceptionInInitializerError: Unable to make field private com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors com.sun.tools.javac.processing.JavacProcessingEnvironment.discoveredProcs accessible: module jdk.compiler does not “opens com.sun.tools.javac.processing” to unnamed module

JDK对应的Class File版本信息

JDK版本Class File版本
1.0.245
1.145
1.246
1.347
1.448
5.049
650
751
852
953
1054
1155
1256
1357
1458
1559
1660
1761
1862
1963
2064
2165