23

由于公共 Java 6 SE JRE 越来越接近它的 EOL(2012 年 11 月),我正在考虑将我的项目从 Java 6 移植到 Java 7。如果 Apple 提供 Java 7 JRE,这没什么大不了的对于 Mac OS X。但由于 Apple 不愿意这样做,我仍然必须支持只有 Java 6 JRE 的用户。

有没有办法用 Java 7 javac 编译 Java 6 兼容的二进制文件(类文件)?当然,我知道这样做时我不能使用新的 Java 7 功能。

感谢期待!

4

4 回答 4

21

这取决于。如果您的程序不使用新的 Java 7 语言扩展,那么您可以使用-source 1.6-target 1.6选项运行 Java 编译器。但是如果你使用 Java 7 语言扩展那么-source 1.6会导致编译错误。

当然,我知道这样做时我不能使用新的 Java 7 功能。

这包括 Java 7 语言特性……以及对标准类库 API 的 Java 7 更改的依赖。另请注意,存在少量行为差异(也称为 API 错误修复)可能会导致代码在 Java 6 和 Java 7 上以不同方式运行。它们应在 Java 6 到 Java 7 转换文档中进行描述。


更新- 无论如何,这对您来说可能不再是问题,因为 Oracle 已经发布了适用于 Mac OSX 的 Java 7。

于 2012-04-11T14:24:08.120 回答
5

我已经安装了jdk6。如果您查看 javac 的手册页:

Cross-Compilation Options
          By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compil‐
          ing, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath
          and -extdirs when cross-compiling; see Cross-Compilation Example below.

         -target version
            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) and 1.6 (also 6).
于 2012-04-11T14:24:18.833 回答
3

是的,但在某些情况下不是。在 java 1.6 中,它们没有资源尝试、字符串切换或多捕获语句等。因此程序的这些部分将无法编译。但是java的思想是编译一次,到处运行;所以代码可以在旧的 JVM 上运行

于 2012-04-11T14:27:58.663 回答
3

Stephen C 的回答是正确的,但并不完整。如果您的 Java 7 程序使用 Java 7 语言功能,它们将无法在 Java 6 中编译,但请注意,一个开发人员在 Java 6 中编码和另一个在 Java 7 中编译时仍可能出现其他细微的错误。

以 java.sql.Driver 为例。在 Java 7 中,该接口获得了一个额外的方法。

Java 7 开发人员 该开发人员实现了 Driver 接口,并在实现的附加 Driver 方法上使用了“Override”注解。该程序作为 Java 6 程序编译得很好,因为 Java 6 编译器看到的类确实具有该方法并且代码被检入。将程序编译为 Java 6 并不意味着 Java 6 编译器会自动切换到使用 Java 6 源代码!

Java 6 开发人员 Java 6 开发人员尝试构建 Java 7 开发人员提交的代码并得到编译错误,即使 Java 7 开发人员没有实现任何 Java 7 语言结构。

因此,即使您可以将其编译为 Java 6,我也建议您不要这样做。

于 2013-07-30T18:32:54.140 回答