java反射的補充:橋接方法以及Spring中一些工具類

來源:互聯網
上載者:User

標籤:

在上一篇博文中: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中一些工具類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.