javareflectionstubbingjava-bridge-method

Writing Synthetic/Bridge method in java


I am writing an application which checks if the method is sythentic or bridge. For testing this application I have added various methods in my stub. But for none of the method this block is getting covered in the test case. Stub contains methods like validate(Object o) ,etc its just like any other normal java class.

What kind of method should I add in my stub so this line will get covered?

code :

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

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

Solution

  • Bridge methods in Java are synthetic methods, which are necessary to implement some of Java language features. The best known samples are covariant return type and a case in generics when erasure of base method's arguments differs from the actual method being invoked.

    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;
        }
    }
    


    See Also