Java中代理的簡明使用

來源:互聯網
上載者:User

標籤:oca   voc   style   邏輯   invoke   final   調用   dem   nts   

代理

     首先應該明確兩個概念

       代理對象:對訪問目標對象進行攔截的對象

       目標對象:實際要訪問的對象

      代理的作用

          可以用對方法的加強;

     動態代理demo

    

//目標對象public class Target implements Itarget{@Overridepublic void test1() {System.out.println("目標對象的test1()");}}

  

//代理對象public class ProxyDemo1 {    @Test    public void test1(){        //建立動態代理對象        final Target tar=new Target();//在匿名內部類被調用,加final修飾        Itarget newProxyInstance =  (Itarget) Proxy.newProxyInstance(tar.getClass().getClassLoader(), //傳遞一個和目標一致的類載入器                                tar.getClass().getInterfaces(), //傳遞一個一個Class<?>[] interfaces                                new InvocationHandler() {//使用匿名內部類實現介面InvocationHandler                                                                        @Override                                    public Object invoke(Object proxy, Method method, Object[] args)                                            throws Throwable {                                        System.out.println("調用目標方法前的邏輯");                                        Object invoke = method.invoke(tar, args);                                        System.out.println("調用目標方法前的邏輯");                                        return invoke;                                    }                                }                                );        newProxyInstance.test1();//實際調用了InvocationHandler下的invoke            }}
//執行結果
調用目標方法前的邏輯目標對象的test1()調用目標方法前的邏輯

 

      注意:jdk的Proxy方式實現的動態代理目標對象必須有介面,沒有介面不能實現jdk

     版本的動態代理.

Java中代理的簡明使用

聯繫我們

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