前言:最初接触到这两个选项是在学习Maven的时候,需要配置pom.xml文件的maven.compiler.source和maven.compiler.target,当时没有深入了解,只是简单的设置为我当前使用的jdk版本8。没有出现任何问题,也就没有进一步探究。然而,今天在看JVM书籍时,在介绍Class文件内容的部分又看到关于source和target的相关介绍,我觉得是时候进行总结了。
概述
source 指定源代码使用的最高语言特性所属的Java SE版本(同JDK版本)
target 指定Class字节码可以运行的最低虚拟机版本
一 .Javac编译器
语法格式:
javac [options] [sourcefiles]
options 选项,也就是我们编译时使用的参数,例如我们常用的选项-encoding指定字符编码、-classpath指定类加载路径。
source和target是编译器的参数,我们平时并不常用到。
1、source 选项
参考官方文档
-source release (release表示JDK发行的版本号,例如1.8)
Specifies the version of source code accepted.(指定可接受的源文件版本)
The following values for release are allowed:
- 1.6 / 6 No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors instead of warnings as was done in earlier releases of Java Platform, Standard Edition.
- 1.7/7 The compiler accepts code with features introduced in Java SE 7.
- 1.8/8 The compiler accepts code with features introduced in Java SE 8.
- 9 The compiler accepts code with features introduced in Java SE 9.
- 10 The compiler accepts code with features introduced in Java SE 10.
- 11 The default value. The compiler accepts code with features introduced in Java SE 11.
如何理解指定可接受的源文件版本呢?
在可以设置的release部分,有这样一句描述:
The compiler accepts code with features introduced in Java SE ${version}
编译器接受带有某版本Java SE中引入的特性的代码
我觉得最重要的是要理解“accept”一词,查看词典
V-T If a person, company, or organization accepts something such as a document, they recognize that it is genuine, correct, or satisfactory and agree to consider it or handle it.
如果一个人、公司或组织接受某样东西,比如一份文件,他们认为或者识别它是真实的、正确的或令人满意的,并同意考虑或处理它。
Java各个发布版本的语言特性(features),如下图所示(详细信息可参考【Java语言特性】):
假如,我本地系统上安装了JDK 1.8,我编写的代码并没有使用Java SE 8中提供的语言特性,但是我使用了Java SE 5中提供的语言特性:泛型。这时我编译该代码时可以使用-