问题描述
虽然告诉我,确实有可能使用--target
和--source
以及较新的--release
命令将较新的版本编译为较旧的版本。
Java 10和Java 8在设置上有很大的不同。
10个使用模块,而8个没有。
我已经加入这个尝试sourceCompatibility = 1.8
到我build.gradle
,我收到一个modules are not supported in -source 8
错误。
这当然是预料之中的,并且是有道理的。
我可以做类似的事情,还是做完全一样的事情,以便可以在Gradle汇编任务中输入var,以在Java 8和Java 10编译代码之间“切换”?
1楼
事实证明我可以。 我输入了这个问题,然后进行了更多研究。 唯一的警告是您不能使用任何更高级别的Java添加。
使用Gradle,我在run语句中包含了一个变量,类似于此gradle clean assemble -PjavaVer=8
使用该变量,我基本上可以关闭要运行的代码。 请参见下面的示例。
if(project.hasProperty('javaVer') && javaVer == '8') {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
afterEvaluate {
repositories {
mavenCentral()
jcenter()
flatDir {
dirs 'lib'
}
}
compileJava {
if (project.hasProperty(('javaVer')) && javaVer == '8') {
excludes = ['**/module-info.java']
} else {
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
]
classpath = files()
}
}
}
}
这将检测变量是否设置为8
,如果是,则排除module-info.java
类,并将sourceCompatibility
和targetCompatibility
设置为1.8
。
这对我有用。
请注意,如果使用Java 10或9特定代码,即Java 10的var
,则不能执行此操作。这就是我们必须排除module-info.java
类的原因,因为它是Java 9中引入的。
希望这对其他人有帮助。
2楼
也许这对您很有用-使用最新的Gradle Modules插件 (自版开始),您实际上可以编译:
-
您的主要代码(
module-info.java
除外)到Java 8, -
您的
module-info.java
,分别连接到Java 9。
这是通过方法自动完成的。
这是一个如何将插件应用于一个人的主build.gradle
(假设它是一个多项目的build):
plugins {
// your remaining plugins here
id 'org.javamodularity.moduleplugin' version '1.5.0' apply false
}
subprojects {
// your remaining subproject configuration here
apply plugin: 'org.javamodularity.moduleplugin'
modularity.mixedJavaRelease 8 // sets "--release 8" for main code, and "--release 9" for "module-info.java"
// test.moduleOptions.runOnClasspath = true // optional (if you want your tests to still run on classpath)
}