Java動態代理

來源:互聯網
上載者:User

標籤:one   row   static   ide   rgs   tproxy   --   tin   ant   

首先我們定義一個介面

public interface SayService {    public void say();}
View Code

接著實現這個介面

public class SayImpl implements SayService {    @Override    public void say() {        System.out.println("I want to go shoping.");    }}
View Code

定義一個動態代理類了,每一個動態代理類都必須要實現 InvocationHandler 這個介面

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class DynamicProxy implements InvocationHandler {    //我們要代理的真實對象    private Object object;        public  DynamicProxy(Object object) {        this.object = object;    }        @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {                System.out.println("before go shoping");        //當代理對象調用真實對象的方法時,其會自動跳轉到代理對象關聯的handler對象的invoke方法進行調用        method.invoke(object, args);        System.out.println("after go shoping");        return null;    }}
View Code

 

 

定義測試方法

public class TestProxy {    public static void main(String[] args) {                //要代理的對象        SayService sayImpl = new SayImpl();                //要代理哪個對象,就要將改對象傳進去,最後是通過其真實對象來調用方法的        InvocationHandler handler = new DynamicProxy(sayImpl);                //Proxy.newProxyInstance--建立代理對象        //handler.getClass().getClassLoader()---載入代理對象        //sayImpl.getClass().getInterfaces()--為代理對象提供的介面是真實對象所實現的介面,表示我們要代理的是改真實對象,這樣我們就能調用介面中的方法        //handler-關聯上的InvocationHandler這個對象        SayService sayService = (SayService)Proxy.newProxyInstance(handler.getClass().getClassLoader()                ,sayImpl.getClass().getInterfaces(), handler);        sayService.say();            }}
View Code

 控制台列印的日誌

before go shoping
I want to go shoping.
after go shoping

 

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.