考慮以下兩類:爲什麼不能使用具有多態返回類型的基本類型?
public interface Foo<T>
{
public T moo();
}
public class IntFoo implements Foo<Integer>
{
public int moo()
{
return 0;
}
}
該代碼將在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;
}
}
這也要做,因爲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字節碼)中實現這個功能:
很高興知道syntetic bridge方法,這對我來說是新的。 – Mifeet