標籤:
在上一篇博文中:http://www.cnblogs.com/guangshan/p/4660564.html
源碼中有些地方用到了
this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
那麼bridgedMethod是什麼呢?
經尋找發現,這個叫做橋接方法:http://freish.iteye.com/blog/1158008
java編譯器採用bridge方法來相容本該使用泛型的地方使用了非泛型的用法的問題。
如下代碼:
public class TestBridgeMethod { public static void main(String[] args) { 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; }}
p引用的是S的對象,但S的test方法傳回值是String,在jdk1.4中沒有泛型,就不會對p.test(new Object());進行檢查,這樣在調用的時候就會報ClassCastException
聲明p的時候使用P<String> p就不會有這樣的問題了。
為了相容非泛型的代碼,java編譯器為test產生了兩個方法。看下面的代碼:
import java.lang.reflect.Method;import java.util.Arrays;public class TestBridgeMethod { 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()); } }}class P<T> { public T test (T t){ return t; }}class S extends P<String> { @Override public String test(String t) { return t; }}
運行結果為:
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。
之前提到的沒有正確使用泛型時會導致越過類型檢查,就是橋接方法引起的。
還有一些很有用的spring源碼中的util工具集合:
http://www.cnblogs.com/younggun/p/3247262.html
java反射的補充:橋接方法以及Spring中一些工具類