考虑以下两个类:
public interface Foo<T>
{
public T moo();
}
public class IntFoo implements Foo<Integer>
{
public int moo()
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码将产生错误,表示与重写方法的返回类型不兼容.严格来说,这是事实,因为并不直接相等.但是,我们都知道可以使用auto(un)boxing将它们隐式转换为彼此.更少知道的是编译器在此示例中生成桥接方法:public
int
moo
int
Integer
int
Integer
public class IntFoo implements Foo<Integer>
{
public <synthetic> <bridge> Object moo()
{
return this.moo(); // upcast
}
public Integer moo() {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
必须这样做是因为JVM在解析方法时区分返回类型,并且由于擦除了返回类型Foo.moo
is Object
,编译器生成了具有与方法相同签名的桥接方法.
我想知道为什么这对原始多态返回类型也不起作用:
public class IntFoo implements Foo<Integer>
{
public <synthetic> <bridge> Object moo()
{
return Integer.valueOf(this.moo());
}
public …
Run Code Online (Sandbox Code Playgroud)