根据客户需求,我目前停留在Java 6上,因此现在使用Gradle 2.14.1。为了能够将Gradle升级到最新版本,并且仍然可以针对Java 6进行编译和测试,我按照官方用户指南中的说明进行操作–请参见Groovy Cross Compilation。
从我的角度来看,通过上述配置,编译以下示例Groovy类应该导致错误,因为它使用Java 8中引入的类。
df2
但是以某种方式Gradle构建成功。我在这里想念什么吗?我该如何使用最新的Gradle版本并仍然针对Java 6编译和测试Groovy源文件和Java源文件?
如果将上述类转换为Java类,则构建会像预期的那样失败。
我还创建了一个小测试项目来演示我的问题。可以在这里找到项目– Github。
谢谢。
答案 0 :(得分:1)
过去几年来,我一直生活在类似的情况中。
为了弄清楚这一点,我创建了一个带有以下build.gradle
文件的示例小型项目:
apply plugin: 'groovy'
repositories {
jcenter()
mavenCentral()
}
dependencies {
compile "org.codehaus.groovy:groovy:2.4.15"
}
if (JavaVersion.current() != JavaVersion.VERSION_1_6) {
// findJava6Jvm is defined in java-versions.gradle
// and returns a gradle JavaInfo instance.
def java6Jvm = findJava6Jvm()
if (!rootProject.ext.has('hasPrintedJavaVersionNote')) {
println "**************** java version notice ****************"
println "NOTE: the gradle process and the source compilation"
println " are using different versions of java:"
println ""
println " gradle process uses: ${JavaVersion.current()}"
println " source complilation uses: 1.6"
println ""
println "*****************************************************"
rootProject.ext.hasPrintedJavaVersionNote = true
}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
tasks.withType(AbstractCompile) {
options.with {
fork = true
forkOptions.executable = java6Jvm.javacExecutable
}
}
tasks.withType(GroovyCompile) {
groovyOptions.with {
fork = true
}
}
tasks.withType(Javadoc) {
executable = java6Jvm.javadocExecutable
}
tasks.withType(Test) {
executable = java6Jvm.javaExecutable
}
tasks.withType(JavaExec) {
executable = java6Jvm.javaExecutable
}
}
def findJava6Jvm(Closure extraUsage = null) {
if (JavaVersion.current().isJava6()) {
// if we are already using java 6 to launch gradle, just return
// the javac for the current jvm
return org.gradle.internal.jvm.Jvm.current()
}
def failOnCondition = { condition, msg ->
if (condition) {
println """
Executing the gradle build with a JDK different from java 1.6
(i.e. java 7, 8, etc) requires that you provide the build
with enough information so that it can still locate a java 1.6
jdk for source code compilation.
If the build can not locate a java 6 jdk, you can help it out by
specifying one of the following properties:
JAVA_HOME_6 environment variable (example: \"export JAVA_HOME_6=/usr/lib/jvm/java-6/\")
JAVA_HOME_6 system property (-DJAVA_HOME_6=<path>)
JAVA_HOME_6 gradle project property (-PJAVA_HOME_6=<path>)
""".stripIndent()
if (extraUsage != null) {
extraUsage()
}
println msg.stripIndent()
throw new GradleException("No 1.6.x jdk found!")
}
}
def name = 'JAVA_HOME_6'
def custom = [System.env[name], System.properties[name], properties[name]].find { it }
failOnCondition !custom, """
ERROR: Please set the JAVA_HOME_6 property in one of the above specified
ways"""
def jdkDir = file(custom)
failOnCondition !jdkDir.isDirectory(), """
ERROR: The configured JAVA_HOME_6 setting:
$custom
does not point to a directory on the local file system.
Please set this variable to the JAVA_HOME of a 1.6.x
jdk"""
def fs = File.separator
def jdkJavac = file("$jdkDir${fs}bin${fs}javac").canonicalFile
if( !jdkJavac.isFile() ) jdkJavac = file( jdkJavac.path + ".exe" )
failOnCondition !jdkJavac.isFile(), """
ERROR: Could not locate a bin/javac executable file under
the configured JAVA_HOME_6 setting:
$custom \n"""
def process = [jdkJavac, "-version"].execute()
process.waitForOrKill(5000)
def version = process.err.text.readLines().first()
failOnCondition !version?.contains('1.6.'), """
ERROR: The configured JAVA_HOME_6 setting:
$custom
points at a non 1.6 jdk, 'java -version' reports $version!"""
// after all the validations pass, reutrn the jdk javac path
org.gradle.internal.jvm.Jvm.forHome(jdkDir)
}
我将您问题中的班级放在文件中:
java-version-experiment ~> tree src/
src/
└── main
└── groovy
└── com
└── somepackage
└── SomeGroovyClass.groovy
鉴于上述情况,当我使用Java 8运行gradle编译源代码时:
java-version-experiment ~> export JAVA_HOME_6=/usr/lib/jvm/java-6_121-oracle
java-version-experiment ~> setjava java-8-oracle
PATH updated - JAVA_HOME=/usr/lib/jvm/java-8-oracle
java-version-experiment ~> gradle -v
------------------------------------------------------------
Gradle 4.10.2
------------------------------------------------------------
Build time: 2018-09-19 18:10:15 UTC
Revision: b4d8d5d170bb4ba516e88d7fe5647e2323d791dd
Kotlin DSL: 1.0-rc-6
Kotlin: 1.2.61
Groovy: 2.4.15
Ant: Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM: 1.8.0_201 (Oracle Corporation 25.201-b09)
OS: Linux 4.18.0-17-generic amd64
java-version-experiment ~> gradle build
> Configure project :
**************** java version notice ****************
NOTE: the gradle process and the source compilation
are using different versions of java:
gradle process uses: 1.8
source complilation uses: 1.6
*****************************************************
BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
java-version-experiment ~>
似乎该类确实是使用Java 6编译的。在Linux上,您可以使用命令行十六进制编辑器对类文件进行检查:
~> od -j 7 -N 1 -t d1 build/classes/groovy/main/com/somepackage/SomeGroovyClass.class
0000007 50
0000010
~>
实质上是从类文件中提取字节7(从零开始),其中50
是我们感兴趣的。相关的Java版本号是:
Java 6 uses major version 50
Java 7 uses major version 51
Java 8 uses major version 52
Java 9 uses major version 53
Java 10 uses major version 54
Java 11 uses major version 55
换句话说,在我看来,在编译任务上使用forkOptions.executable
可以正常工作,并且确实使用Java 6来编译类。
但是,在我看来,类路径也泄漏了。我的意思是,即使您使用Java 6可执行文件进行编译,似乎Java 8类路径和API也会泄漏到编译过程中。
就像您说的那样,以上编译应该会失败,但是没有失败。我仍然不知道为什么会发生这种情况,更重要的是如何防止类路径泄漏。
任何gradle大师都可以在这里随意鸣叫,我将非常有兴趣深入了解本期。
<<编辑>>
发现以下内容:
针对Java 6或Java 7的编译和测试
Groovy编译器将始终与用于启动Gradle的Java版本一起执行。您应该将sourceCompatibility和targetCompatibility设置为1.6或1.7。如果您还具有Java源文件,则可以按照与Java插件相同的步骤操作,以确保使用正确的Java编译器。
在gradle文档中:
https://docs.gradle.org/current/userguide/groovy_plugin.html
所以看来这不太可能。类文件中的第7个字节似乎由以下内容控制:
targetCompatibility = JavaVersion.VERSION_1_6
设置,即,即使使用纯Java 8并设置targetCompatibility,我们也会在类主版本字节中获得50
。
<<编辑2 >>
确认这适用于Java文件。在src/main/java/com/somepackage/SomeJavaClass.java
下添加了一个Java文件,该文件具有与上述配置文件完全相同的构建文件,以配置双vm编译方案。
结果:
gradle clean build
> Configure project :
**************** java version notice ****************
NOTE: the gradle process and the source compilation
are using different versions of java:
gradle process uses: 1.8
source complilation uses: 1.6
*****************************************************
> Task :compileJava FAILED
/home/mbjarland/projects/java-version-experiment/src/main/java/com/somepackage/SomeJavaClass.java:5: cannot find symbol
symbol : class Optional
location: class com.somepackage.SomeJavaClass
public Optional<String> someJavaMethod() {
^
/home/mbjarland/projects/java-version-experiment/src/main/java/com/somepackage/SomeJavaClass.java:6: cannot find symbol
symbol : variable Optional
location: class com.somepackage.SomeJavaClass
return Optional.empty();
^
2 errors
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed with exit code 1; see the compiler error output for details.
BUILD FAILED in 1s
2 actionable tasks: 2 executed
这就是您所期望的。
经过长时间探索后得出的结论:这按预期适用于Java文件,而不适用于Groovy文件。