【发布时间】:2015-09-06 09:42:14
【问题描述】:
考虑以下两个类:
public interface Foo<T>
{
public T moo();
}
public class IntFoo implements Foo<Integer>
{
public int moo()
{
return 0;
}
}
此代码将在publicintmoo 产生错误,表示int 与被覆盖方法的返回类型Integer 不兼容。严格来说,这是真的,因为int 不直接 等于Integer。但是,我们都知道可以使用自动(取消)装箱将它们隐式转换为彼此。鲜为人知的是编译器在这个例子中生成了一个桥接方法:
public class IntFoo implements Foo<Integer>
{
public <synthetic> <bridge> Object moo()
{
return this.moo(); // upcast
}
public Integer moo() {
return 0;
}
}
必须这样做是因为 JVM 在解析方法时会区分返回类型,并且由于 Foo.moo 的擦除返回类型是 Object,因此编译器生成了一个与方法具有相同签名的桥接方法。
我想知道为什么这也不适用于原始多态返回类型:
public class IntFoo implements Foo<Integer>
{
public <synthetic> <bridge> Object moo()
{
return Integer.valueOf(this.moo());
}
public int moo()
{
return 0;
}
}
似乎没有任何理由不拥有此功能:
IntFoo intFoo = new IntFoo();
Foo<Integer> foo = intFoo;
Integer i = foo.moo(); // calls the synthetic method, which boxes the result of the actual implementation
事实上,这个 REPL 会话的屏幕截图表明,我什至能够在我的 custom programming language(编译成 Java 字节码)中实现它:
【问题讨论】:
-
很高兴知道合成桥接法,那对我来说是新的。
标签: java polymorphism primitive return-type