2011-07-19 32 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。我写的代码,但我无法在此评论空间发布。 –