看一下这个(可能是愚蠢的)代码:
public <T extends Appendable & Closeable> void doStuff(T object)
throws IOException{
object.append("hey there");
object.close();
}
我知道编译器会删除通用信息,因此我对与编译器等效的Java 1.4代码很感兴趣(我很确定编译器不会重新排列源代码,因此我需要一个等效的Java源版本像我这样的天真人可以理解的)
是这样的:
public void doStuff(Object object)
throws IOException{
((Appendable)object).append("hey there");
((Closeable)object).close();
}
或者更像这样:
public void doStuff(Object object)
throws IOException{
Appendable appendable = (Appendable) object;
Closeable closeable = (Closeable) object;
appendable.append("hey there");
closeable.close();
}
甚至像这样:
public void doStuff(Appendable appendable)
throws IOException{
Closeable closeable = (Closeable) appendable;
appendable.append("hey there");
closeable.close();
}
还是另一个版本?
最佳答案
该方法的签名看起来像public void doStuff(Appendable appendable)
,因为
(JLS §4.4 Type Variables)
如果您使用反射来访问此方法,则此行为可能很重要。
此行为的另一种用法是保留与前接口(interface)的二进制兼容性,如Generics Tutorial第10节所述(感谢Mark Peters指出)。那是,
public static <T extends Object & Comparable<? super T>> T max(Collection<T> coll)
与返回
Object
的其通用版本二进制兼容。方法主体等效于以下内容,但我认为它是实现的详细信息:
appendable.append("hey there");
((Closeable) appendable).close();
关于java - Java编译器对多个通用范围有什么作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4258447/