java代理基礎類1.0

來源:互聯網
上載者:User

標籤:null   tproxy   instance   ati   handler   錯誤   void   base   賦值   

1.代理的書寫,是比較麻煩的,寫原生代理,又是一件無聊且容易遺漏的事情。寫了一個簡單的代理類,可借鑒也可指出錯誤。

 1 package cn; 2  3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6  7 /** 8  * 代理類的基礎,必須先是設定對象(必須是介面對象賦值實作類別),不然擷取的代理對象會null 指標。 9  * @author jxlys10  *11  */12 public class ProxyBase implements InvocationHandler {13     private Object obj;14 15     public ProxyBase() {16     }17 18     public ProxyBase(Object obj) {19         this.obj = obj;20     }21 22     public Object getObj() {23         return obj;24     }25 26     public void setObj(Object obj) {27         this.obj = obj;28     }29 30     /**31      * 獲得代理對象32      * 33      * @param t34      * @return35      */36     public <T> T getProxy(Class<T> t) {37         return getObject(t, getProxy());38     }39 40     /**41      * 獲得代理對象42      */43     public Object getProxy() {44         return obj != null ? Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this) : null;45     }46 47     // 對象強轉48     @SuppressWarnings("unchecked")49     public <T> T getObject(Class<T> t, Object obj) {50         return obj != null ? (T) obj : null;51     }52   53     public void beforeAction() {54     }55 56     public void afterAction() {57     }58 59     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {60         beforeAction();61         Object invoke = method.invoke(obj, args);62         afterAction();63         return invoke;64     }65 }

調用如下:

 1 interface A { 2     public void say(); 3 } 4  5 class B implements A { 6  7     public void say() { 8         System.out.print("love"); 9     }10 }11 12 public class TestMain {13 14     public static void main(String[] args) {15      A a = new B(); 16         a.say();//未代理17         ProxyBase pbu = new ProxyBase(a) {18             public void beforeAction() {19                 System.out.print("I ");20             }21 22             public void afterAction() {23                 A a = getObject(A.class, getObj());24                 System.out.print(" You!");25             }26         };27         a = pbu.getProxy(A.class);28         pbu = null;//這一步不重要,也可以沒有。29         a.say();// 已代理,也可以用繼承的方式實現代理。  30     }31 }

 

java代理基礎類1.0

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.