码迷,mamicode.com
首页 > 其他好文 > 详细

Method.isBridge()

时间:2015-09-06 13:11:51      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

java编译器采用bridge方法来兼容本该使用泛型的地方使用了非泛型的用法的问题。

 

如下代码:

 

Java代码  技术分享

  1. public class TestBridgeMethod {  

  2.     public static void main(String[] args) {  

  3.         P p = new S();  

  4.         p.test(new Object());  

  5.     }  

  6. }  

  7.   

  8. class P<T> {  

  9.     public T test (T t){  

  10.         return t;  

  11.     }  

  12. }  

  13.   

  14. class S extends P<String> {  

  15.     @Override  

  16.     public String test(String t) {  

  17.         return t;  

  18.     }  

  19. }  

 

p引用的是S的对象,但S的test方法返回值是String,在jdk1.4中没有泛型,就不会对p.test(new Object());进行检查,这样在调用的时候就会报ClassCastException

声明p的时候使用P<String> p就不会有这样的问题了。

 

 

为了兼容非泛型的代码,java编译器为test生成了两个方法。看下面的代码:

Java代码  技术分享

  1. import java.lang.reflect.Method;  

  2. import java.util.Arrays;  

  3.   

  4.   

  5. public class TestBridgeMethod {  

  6.     public static void main(String[] args) {  

  7.         Class<?> clazz = S.class;  

  8.         Method[] methods = clazz.getMethods();  

  9.         for(Method method : methods) {  

  10.             System.out.println(method.getName() + ":" + Arrays.toString(method.getParameterTypes()) + method.isBridge());  

  11.         }  

  12.     }  

  13. }  

  14.   

  15. class P<T> {  

  16.     public T test (T t){  

  17.         return t;  

  18.     }  

  19. }  

  20.   

  21. class S extends P<String> {  

  22.     @Override  

  23.     public String test(String t) {  

  24.         return t;  

  25.     }  

  26. }  

 

 

运行结果为:

 

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


Method.isBridge()

标签:

原文地址:http://my.oschina.net/u/2422498/blog/501627

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!