Android java的動態代理demo(會用到反射)

package com.zzm.myapplication.dynamic_proxy;
import android.util.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyDemo {

    public void startProxy(){

        //建立代理
        Ibuy buyer=new Buyer();

        //建立動態代理handler
        DynamicProxy dynamicProxy=new DynamicProxy(buyer);

        //建立動態代理類
        Ibuy buyerProxy= ((Ibuy) Proxy.newProxyInstance(Ibuy.class.getClassLoader(), new Class[]{buyer.getClass()}, dynamicProxy));

        //執行要被代理的方法
        buyerProxy.buy_phone();
    }

    //代理接口
    public interface Ibuy{
        void buy_phone();
    }

    //被代理類
    public class  Buyer implements Ibuy{
        @Override
        public void buy_phone() {
            Log.i("zzm","幫我買手機三");
        }
    }

    //動態代理handler
    public class DynamicProxy implements InvocationHandler {
        private  Ibuy ibuy;
        public DynamicProxy(Ibuy ibuy){
            this.ibuy=ibuy;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            if("buy_phone".equals(method.getName())){
                Log.i("22m","執行了代理的方法 buy_phone()");
            }
            return method.invoke(ibuy,args);
        }
    }
}
相關文章
相關標籤/搜索