2011-07-19 99 views
4

我正在編寫一個應用程序,用於檢查方法是sythntic還是bridge。 爲了測試這個應用程序,我在我的存根中添加了各種方法。 但是對於這個塊在測試用例中被覆蓋的方法都沒有。 存根包含像validate(Object o)等方法,就像任何其他普通的java類一樣。在java中編寫Synthetic/Bridge方法

我應該在我的存根中添加什麼樣的方法,以便這一行將被覆蓋?

代碼:

 Method[] methods = inputClass.getMethods(); 
     for (Method method : methods) { 

     if (method.isSynthetic() || method.isBridge()) { 
      isInternal = true; 
     } 
     // More code. 
    } 

回答

2

在Java Bridge的方法是人工合成的方法,即以實現一些Java語言特性必要的。最有名的示例是協變返回類型和泛型中的一種情況,當刪除基本方法的參數與正在調用的實際方法不同時。

import java.lang.reflect.*; 

/** 
* 
* @author Administrator 
*/ 
class SampleTwo { 

    public static class A<T> { 

     public T getT(T args) { 
      return args; 
     } 
    } 

    static class B extends A<String> { 

     public String getT(String args) { 
      return args; 
     } 
    } 
} 

public class BridgeTEst { 

    public static void main(String[] args) { 
     test(SampleTwo.B.class); 
    } 

    public static boolean test(Class c) { 
     Method[] methods = c.getMethods(); 
     for (Method method : methods) { 

      if (method.isSynthetic() || method.isBridge()) { 
       System.out.println("Method Name = "+method.getName()); 
       System.out.println("Method isBridge = "+method.isBridge()); 
       System.out.println("Method isSynthetic = "+method.isSynthetic()); 
       return true; 
      } 
     // More code. 
     } 
     return false; 
    } 
} 


請參見

+2

我認爲它看起來像它的共同返回類型。當超類方法返回具有協變量類型的Object和子類覆蓋(例如,對於例如String)時,這對於橋和合成也會返回true。我寫的代碼,但我無法在此評論空間發佈。 –