zoukankan      html  css  js  c++  java
  • Bridge Method

    1.java编译器采用Bridge Method 来兼容本该使用泛型的地方使用了非泛型的问题。

    public class TestBridgeMethod {
        public static void main(String[] args) {
            //p引用的是S的对象,但S的test方法返回值是String
            //在jdk1.4中没有泛型,对p.test(new Object())进行检查会报ClassCastException
            //声明p的时候使用P<String> p就不会有这样的问题了。
            P p = new S();    
            p.test(new Object());
        }
    }
    
    class P<T> {
        public T test (T t){
            return t;
        }
    }
    
    class S extends P<String> {
        @Override
        public String test(String t) {
            return t;
        }
    }

    2.

     public static void main(String[] args) {  
            Class<?> clazz = S.class;  
            Method[] methods = clazz.getMethods();  
            for(Method method : methods) {  
                System.out.println(method.getName() + ":" + Arrays.toString(method.getParameterTypes()) + method.isBridge());  
            }  
        }  

    结果:

    test:[class java.lang.String]  false
    test:[class java.lang.Object]  true
    getClass:[]  false
    hashCode:[]  false
    equals:[class java.lang.Object]   false
    toString:[]  false
    notify:[]  false
    notifyAll:[]  false
    wait:[long, int]  false
    wait:[]  false
    wait:[long]  false

    编译器为S生成了两个test方法:

    一个参数为String,用于泛型

    一个参数为Object,用于非泛型,这个方法就是bridge方法,调用method.isBridge返回true

  • 相关阅读:
    Python 2.7 中使用 Print 方法
    python
    Python 中 global、nonlocal的使用
    PYTHON中 赋值运算的若干问题总结
    Python List 中 Append 和 Extent 方法不返回值。
    由Python的一个小例子想到的
    PHP环境安全加固
    Tomcat服务安全加固
    网站被植入Webshell的解决方案
    Apache服务安全加固
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3840942.html
Copyright © 2011-2022 走看看