有关Java 8向后兼容性的问题:JDK中的新方法 [英] Issue about java 8 backward compatibility: new methods in JDK
问题描述
一个简单的问题.在Java 8中,JDK类中有大量新方法.假设我们使用Java 7(或Java 6)创建了此类:
Simple question. In Java 8 we have huge number of new methods in JDK classes. Say we have created such class, using Java 7 (or Java 6):
class MyArrayList<E> extends ArrayList<E> {
public void sort(Comparator<E> c) {
// some sort
}
}
这是相当合理的实现.现在,我们尝试使用Java 8进行编译并收到预期的编译错误:
This is quite reasonable implementation. Now we try to compile it with Java 8 and receive expectable compile error:
error: name clash: sort(Comparator<E#1>) in MyArrayList and sort(Comparator<? super E#2>) in ArrayList have the same erasure, yet neither overrides the other
public void sort(Comparator<E> c) {
^ where E#1,E#2 are type-variables:
E#1 extends Object declared in class I.MyArrayList
E#2 extends Object declared in class ArrayList
在这里,我想提出两个问题:
Here I would like to arise 2 questions:
-
即使使用JDK 8具有
javac -source 1.7 -target 1.7
选项,我也会收到相同错误-为什么?我认为这些选项应允许编译遗留代码.
Even with
javac -source 1.7 -target 1.7
option using JDK 8 I receive same error - why? I thought these options should allow compile legacy code.
一般来说向后兼容性如何?
How about backward compatibility in general?
编辑,确切地说,可能是我做错了吗? JDK 1.8.0_65,Mac OS X:
EDIT To be precise, may be I'm doing something wrong? JDK 1.8.0_65, Mac OS X:
bash-3.2$ javac -version
javac 1.8.0_65
bash-3.2$ javac -source 1.7 -target 1.7 MyArrayList.java
warning: [options] bootstrap class path not set in conjunction with -source 1.7
MyArrayList.java:7: error: name clash: sort(Comparator<E#1>) in MyArrayList and sort(Comparator<? super E#2>) in ArrayList have the same erasure, yet neither overrides the other
public void sort(Comparator<E> c) {
^
where E#1,E#2 are type-variables:
E#1 extends Object declared in class MyArrayList
E#2 extends Object declared in class ArrayList
1 error
1 warning
推荐答案
-
因为即使有这些选项,您仍在针对Java 8类进行编译. JDK不知道哪种方法出现在哪个版本的JDK中.所有这些选项的作用是告诉编译器在您正在编译的代码中仅接受Java 7语法,并生成Java 7字节码.您将必须传递实际链接到JDK 7类(使用
-bootclasspath
选项)以进行交叉编译.
because even with these options, you're still compiling against the Java 8 classes. The JDK doesn't have any idea which methods appeared in what version of the JDK. All these options do is tell the compiler to accept only Java 7 syntax in the code you're compiling, and to generate Java 7 bytecode. You would have to pass actually link to the JDK 7 classes (using the
-bootclasspath
option) to cross-compile.
是的,这是一个问题.并不是很大,拥有所有新默认方法的好处比拥有一些罕见的非编译代码的不便更为重要.
Yes, it's a problem. Not huge, and the benefit of having all thses new default methods is more important than the inconvenience of having some rare non-compiling code.
这篇关于有关Java 8向后兼容性的问题:JDK中的新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!