简体   繁体   English

在 java 中编写 Synthetic/Bridge 方法

[英]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.存根包含 validate(Object o) 等方法,就像任何其他正常的 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.
     }

Bridge methods in Java are synthetic methods, which are necessary to implement some of Java language features. Java 中的桥接方法是合成方法,是实现 Java 语言特性所必需的。 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.最知名的样本是协变返回类型和 generics 中的一个案例,当擦除基本方法的 arguments 与实际调用的方法不同时。

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也可以看看

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:在这里,我们列出了JDK中的示例 Java 方法标记为ACC_BRIDGE和/或ACC_SYNTHETIC ,因此可以通过反射使用它们来轻松覆盖您的测试用例:

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM