2014-06-11 29 views
2

當實現具有泛型返回類型的方法並反映實現類中聲明的方法時,反射API將返回兩個方法。例如:實現具有通用返回類型的方法時通過反射的多種方法

interface Referenceable<T> { 
    T getReference(); 
} 

class UUIDRef implements Referenceable<UUID> { 
    public UUID getReference() { 
     System.out.println("You called"); 
     return null; 
    } 
} 

@Test 
public void test() throws Exception { 
    UUIDRef ref = new UUIDRef(); 
    for (Method m : UUIDRef.class.getDeclaredMethods()) { 
     System.out.println(String.format("%s %s", m.getReturnType(), m.getName())); 
     m.invoke(ref, null); 
    } 
} 

此輸出:

class java.util.UUID getReference You called class java.lang.Object getReference You called

爲什麼會出現兩種方法已經被宣佈UUIDRef?有沒有什麼方法可以準確地瞭解哪兩個是最精煉的,實際上是在UUIDRef上宣佈的?

+0

您是否嘗試將@Override註釋添加到實現的方法中? – ra2085

+0

我實際上正在編譯1.5,@Override不允許在這裏。 – Jonathan

回答

2

爲了支持協變返回類型,a bridge method must be created能夠在需要聲明返回類型的代碼中調用該方法。

總之,這座橋的方法是,將在以下情況下,其中T被擦除Object調用的方法:

public <T> T doSomething(Referenceable<T> obj) { 
    return obj.getReference(); 
} 

使用m.isBridge()告訴這是橋方法。

+1

以下是參考資料:http://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html –

+0

這是有效的。謝謝! (等待計時器接受答案) – Jonathan

相關問題