Javac选项source和target的作用

前言:最初接触到这两个选项是在学习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中提供的语言特性:泛型。这时我编译该代码时可以使用-

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月几时有666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值