开发者

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 s开发者_StackOverflow社区hould 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.
     }


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

  • #Reference

See Also

  • what-java-lang-reflect-method-isbridge-used-for ?


Here we list example Java methods in JDK is tagged with ACC_BRIDGE and/or ACC_SYNTHETIC, so they can be used via reflection to cover your test case easily:

  • The method java.math.BigDecimal.compareTo(Object) is both ACC_BRIDGE and ACC_SYNTHETIC
  • The method java.lang.AbstractStringBuilder.lambda$chars$0() is ACC_SYNTHETIC

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜