我已经配置了一个持续集成工具(Travis CI)来运行我做的每个提交,它在以下JDK上构建我的Java 6项目:
现在,Travis CI本身并不支持在完成所有任务后上传创建的工件的任务,所以我正在使用解决方法。
我的问题是,解决方法将尝试将已创建为 last 的工件上传到Sonatype快照存储库。
这意味着有一次它会上传由Open JDK 6编译的快照,另一次是Open JDK 7等等。
这有关系吗? Java 6客户端是否可以使用由任何Java 6+ JDK编译的Java 6代码?我们已经知道代码(貌似)完成了它的目的,因为它已编译并且测试已经过了。
Java 6代码可以在任何兼容Java 6的JRE和Android上运行。
答案 0 :(得分:5)
没有。 - 但您必须指定-target
当Java编译类时,它会为目标Java JRE编译它。有关参考,请参阅javac option for javac 1.7(和for Java8 here)
-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), 1.6 (also 6), and 1.7 (also 7). The default for -target depends on the value of -source: If -source is not specified, the value of -target is 1.7 If -source is 1.2, the value of -target is 1.4 If -source is 1.3, the value of -target is 1.4 If -source is 1.5, the value of -target is 1.7 If -source is 1.6, the value of -target is 1.7 For all other values of -source, the value of -target is the value of -source.
因此,只有当代码不使用Java8或更高版本中提供的任何功能时,使用Java目标javac编译的代码(目标为1.7)才能在Java7 JRE上运行。
因此,在您的情况下,使用Java8 JDK编译的代码(如果它没有javac命令的-target参数)将无法在Java6上加载。错误将是:UnsupportedClassVersionError
答案 1 :(得分:2)
如果您在Java 6和Java 8(定义目标版本)中成功构建代码,您可以将代码提供给另一个人,并且只需要他们拥有Java 6+(也设置目标版本)并且它将工作在任何Java 6或更高版本上。
为此,您需要设置-target 1.6 -source 1.6
或在maven-compiler-plugin中指定版本。 (我强烈建议你使用构建工具)
在maven你会设置
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
[...]
</build>
[...]
</project>
任何使用你的构建的人都会创建一个JAR,其字节代码可以在Java 6 +上运行
在Java 8中编译Java 6的字节代码时,可以在Java 6 +上使用
你发现问题的地方是,与Java 6相比,Java 8在JDK中有更多的类和方法。这意味着Java 8编译器将很乐意编译Java 6,它使用Java 8中提供的类,方法或字段但是在Java 6中不可用。
在编译代码时可以告诉Java 8编译器使用Java 6库,但更简单的解决方案是使用Java 6编译器,或者您可以假设这不会发生或者您有其他方法检测到Java 6代码仅使用Java 6可用的库。
您可能会遇到与第三方库相同的问题。您可能正在编译使用Java 8的第三方库版本,但对于Java 6,您必须使用旧版本的库(或者可能不存在)
您将遇到的另一个问题是Java 8修复了Java 6允许的编译器中的一些错误。这些修复非常奇特,您必须编写非标准Java代码(由于编译器中的错误而允许Java 6)
Javadoc默认会抱怨非Stand Javadoc,甚至在Java 6的javadoc通过时也无法构建。