Java中source选项的用法,关于java:使用-source和-target javac选项进行编译

本问题已经有最佳答案,请猛点这里访问。

我已将Web应用程序升级到Java 7,JAVA_HOME指向1.7。 我的Maven插件正在从java_home读取Java版本。 但是在pom.xml中看到以下设置后我有点困惑:

org.apache.maven.plugins

maven-compiler-plugin

2.3.2

true

1.6

1.6

1.6

如果按原样保留上述设置,Maven是否会使用1.6或1.7编译Java代码? 根据我对此链接的理解,上述设置将获得优先权,项目将使用1.6而不是1.7进行编译。 那是对的吗?

如果我给出如下设置,如果我有特定于JDK 1.7的代码,我的代码现在会编译吗?

1.6

1.7

我不确定; 上述设置实际意味着什么?

stackoverflow.com/questions/8750563/maven-doesnt-use-java-7

我的代码现在会编译吗? - 是的,但仅限于JDK 1.7

没有插件的编译器配置

1.7

1.7

javac -help

javac -help

-source          Provide source compatibility with specified release

-target          Generate class files for specific VM version

javac - Java编程语言编译器文档

source Specifies the version of source code accepted. The following values for release are allowed:

1.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 in previous releases of Java SE.

6 Synonym for 1.6.

1.7 This is the default value. The compiler accepts code with features introduced in Java SE 7.

7 Synonym for 1.7.

target Generate class files that target a specified version of the VM. Class files will run on the specified target and on later versions, but not on earlier versions of the VM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7).

The default for -target depends on the value of -source:

兼容性

Java SE 7和JDK 7兼容性

JDK"向上"还是"向后"兼容?

java 7语言向后兼容性

Java SE 7的功能和增强功能

JDK 1.6和1.7中的新功能

使用您拥有的设置,源代码将被解释为符合Java 1.6,并且生成的类将以1.6 JVM为目标。 JDK 1.7可以处理它。但是如果你的代码是1.7并且想要只针对1.7,那么你应该在两者中写入1.7。请注意,如果您的源代码包含仅在1.7中可用的功能,例如菱形运算符,那么您将收到编译错误。

随着设置

1.6

1.7

以下1.7代码(钻石运营商)

List l = new ArrayList<>();

将无法编译,并出现以下错误:

... Compilation failure

... App.java:[14,40] diamond operator is not supported in -source 1.6

(use -source 7 or higher to enable diamond operator)

以下代码将编译得很好

List l = new ArrayList();

设置:

1.7

1.6

以下1.7代码(钻石运算符)

List l = new ArrayList<>();

也将无法使用以下错误进行编译:

source release 1.7 requires target release 1.7

因此,如果您想使用1.7的源功能(菱形运算符,资源尝试等),那么您必须在pom.xml中包含以下内容。

1.7

1.7

请查看我的更新,让我知道你对此的看法

@MSach请检查我的编辑。

是的,这会将您的代码编译为Java 1.6代码(也将在Java 7环境中运行)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值