【问题标题】:Writing Synthetic/Bridge method in java在java中编写合成/桥接方法
【发布时间】:2011-10-08 09:31:55
【问题描述】:

我正在编写一个应用程序来检查该方法是合成的还是桥接的。 为了测试这个应用程序,我在我的存根中添加了各种方法。 但是对于任何方法,这个块都没有被覆盖在测试用例中。 存根包含 validate(Object o) 等方法,就像任何其他普通的 java 类一样。

我应该在我的存根中添加什么样的方法才能覆盖这条线?

代码:

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

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

【问题讨论】:

标签: java reflection stubbing java-bridge-method


【解决方案1】:

Java 中的桥接方法是合成方法,它是实现某些 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;
    }
}


另见

【讨论】:

  • 我认为它看起来像它的 co-veriant 返回类型。当超类方法返回 Object 并且子类覆盖具有协变类型(例如字符串)时,这对于桥接和合成也返回 true。我已经编写了代码,但我无法在此评论空间中发布。
【解决方案2】:

这里我们列出了JDK 中带有ACC_BRIDGE 和/或ACC_SYNTHETIC 标记的示例Java 方法,因此可以通过反射使用它们来轻松覆盖您的测试用例:

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-27
    • 2019-02-12
    • 1970-01-01
    • 2013-10-12
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多