如何为 Java 11 编译和运行我的 Maven 单元测试,同时为旧版本的 Java 8 编译我的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24323176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compile and run my Maven unit tests for a Java 11, while having my code compiled for an older version of Java 8
提问by rjdkolb
I want to use Java 11 syntax in my unit tests, but my 'main' code needs to be compiled for Java 8 since my production environment only has JDK 8 installed.
我想在我的单元测试中使用 Java 11 语法,但我的“主”代码需要为 Java 8 编译,因为我的生产环境只安装了 JDK 8。
Is there a way of doing this with the maven-compiler-plugin? My Jenkins server has Java 11 installed.
有没有办法用 maven-compiler-plugin 做到这一点?我的 Jenkins 服务器安装了 Java 11。
I will accept the risk that I can accidental use Java 11 specific functionality in my production code.
我将接受在生产代码中意外使用 Java 11 特定功能的风险。
采纳答案by mkrakhin
In Maven compile and testCompile goals are different. And Maven even has parameters for testCompile: testTarget and testSource. So:
在 Maven 中 compile 和 testCompile 目标是不同的。Maven 甚至还有 testCompile 的参数:testTarget 和 testSource。所以:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<testSource>1.8</testSource>
<testTarget>1.8</testTarget>
</configuration>
</plugin>
回答by rjdkolb
A slightly more terse version of mkrakhin's answer You can set the source, target, testSourceand testTarget:
mkrakhin 答案的更简洁版本您可以设置source、target、testSource和testTarget:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.testSource>11</maven.compiler.testSource>
<maven.compiler.testTarget>11</maven.compiler.testTarget>
</properties>
</project>