What is the relationship/difference between sourceCompatibility and targetCompatibility?
What happens when they are set to different values?
Accoording to Gradle documentation:
sourceCompatibility is "Java version compatibility to use when compiling Java source."
targetCompatibility is "Java version to generate classes for."
My understanding is that targetCompatibiliy will generate java bytecode that is compatible with a specific version of Java, is this a subset of the functionality of sourceCompatibility
?
——From this question of stackoverflow
One of the answers
sourceCompatibility = specifies that version of the Java programming language be used to compile .java files. e.g sourceCompatibility 1.6 =specifies that version 1.6 of the Java programming language be used to compile .java files.
By default sourceCompatibility = "version of the current JVM in use" and targetCompatibility = sourceCompatibility
targetCompatibility = The option ensures that the generated class files will be compatible with VMs specified by targetCompatibility . Note that in most cases, the value of the -target option is the value of the -source option; in that case, you can omit the -target option.
Class files will run on the target specified by targetCompatibility and on later versions, but not on earlier versions of the VM
简单翻译就是
sourceCompatibility:指定编译.java文件的jdk版本
targetCompatibility:确保.class文件与targetCompatibility所指定版本或者更新版本的java虚拟机兼容
但是
compileOptions {
sourceCompatibility 1.6
targetCompatibility 1.7
}
//不报错,编辑的时候用的是JDK1.6(只能用JDK1.6的特性),生成的是1.7的.class文件
compileOptions {
sourceCompatibility 1.6
targetCompatibility 1.8
}
//不报错,编辑的时候用的是JDK1.6(只能用JDK1.6的特性),生成的是1.8的.class文件,需要Build Tools 24.0.0 or later,使用Jack工具链
compileOptions {
sourceCompatibility 1.7
targetCompatibility 1.8
}
//不报错,编辑的时候用的是JDK1.7,生成的是1.8的.class文件,需要Build Tools 24.0.0 or later,使用Jack工具链
compileOptions {
sourceCompatibility 1.7
targetCompatibility 1.6
}
//报错,如下图(1.6是1.8而已)。但是用Jack工具链不报错。
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.7
}
//报错,如下图(1.6是1.8而已)。但是用Jack工具链不报错。
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.6
}
//报错,如下图。但是用Jack工具链不报错。
** 综上所述 **
- 使用dx工具,则要求targetCompatibility>=sourceCompatibility,否则报错,
但是这里报错的根本原因不在于dx,而在于JDK的javac工具,其不支持targetCompatibility<sourceCompatibility的情况###
- 使用Jack工具链,则没有上述要求,
而使用Jack工具链不报错的根本原因是Jack (.java → .jack → .dex),压根就不会生成.class文件,这里的targetCompatibility 也就失效了。###
关于Jack,请看下篇文章Who is Jack?
由此可见,对于Android程序员而言,这个targetCompatibility我们不太需要关心,我们程序的向前兼容最直接取决于minSdkVersion,所以Android中建议targetCompatibility=sourceCompatibility