如何在 Gradle 构建中指定所需的 Java 版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27861658/
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 specify the required Java version in a Gradle build
提问by pditommaso
I would like to set in a Gradle build file the required Java version e.g. 7 or 8 withouthaving to specify the actual path to a local JDK installation.
我想在 Gradle 构建文件中设置所需的 Java 版本,例如 7 或 8,而不必指定本地 JDK 安装的实际路径。
Is this possible ?
这可能吗 ?
回答by dhfsk
TLDR; Thanks @franklin-yu "targetCompatibility = '1.7' -> your user can compile with 8 and run with 7."
TLDR;谢谢@franklin-yu“targetCompatibility = '1.7' -> 你的用户可以用 8 编译并用 7 运行。”
See Gradle, "sourceCompatibility" vs "targetCompatibility"?
看到Gradle,“sourceCompatibility”与“targetCompatibility”?
targetCompatibility = '1.7'
does the trick for e.g. Java 7
targetCompatibility = '1.7'
例如 Java 7 的技巧
Use sourceCompatibility = '1.7'
for the language level
使用sourceCompatibility = '1.7'
的语言水平
回答by Rosberg Linhares
You can try this:
你可以试试这个:
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<JavaCompile> {
options.compilerArgs.addAll(arrayOf("--release", "8"))
}
This will also give JDK compliance to you. You can also see the following related issues:
这也将为您提供 JDK 合规性。您还可以看到以下相关问题:
- Gradle: [Java 9] Add convenience method for
-release
compiler argument - Eclipse Plug-ins for Gradle: JDK API compatibility should match the sourceCompatibility option.
- Gradle:[Java 9] 为
-release
编译器参数添加便捷方法 - Gradle 的 Eclipse 插件:JDK API 兼容性应与 sourceCompatibility 选项匹配。
回答by Pieter12345
In the build.gradle
file, add the following two lines:
在build.gradle
文件中,添加以下两行:
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
The targetCompatibility
defines the generated JVM bytecode version (this is the version that users of your application need). The sourceCompatibility
defines which source code constructs are allowed (e.g. you need Java 1.8 or higher to use lambda expressions in source code).
该targetCompatibility
定义生成JVM字节码的版本(这是版本的应用程序需要用户)。该sourceCompatibility
源代码结构允许定义(例如你需要的Java 1.8或更高版本才能使用lambda表达式在源代码中)。