JDK動態代理

核心類:

  • java.lang.reflect.Proxy
  • java.lang.reflect.InvocationHandler

JDK動態代理要點:

  • 被代理對象要實現接口
  • 必須實現java.lang.reflect.InvocationHandler類並重寫invoke方法
  • invoke方法裏可以對要代理的對象進行增強,invoke方法的第2個參數method就是被代理對象要增強的方法,調用前需要與被代理對象綁定,也就是要往method.invoke()的第一個參數傳遞被代理對象
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyPattern {
    static interface IService{
        void doSomePost();
    }

    static class Serviceimp implements IService{
        public void doSomePost(){
            System.out.println("提交表單更新數據");
        }
    }

    static class EnhanceProxy{
        private IService service = new Serviceimp();
        public void preEnhanceMethod(){
            InvocationHandler handler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 在此處可以添加被代理對象的增強行爲
                    System.out.println("前置增強效果:");
                    System.out.println("檢查用戶是否有權限更新數據");
                    return method.invoke(service, args);
                }
            };
            IService proxy = (IService) Proxy.newProxyInstance(service.getClass().getClassLoader(),
                    service.getClass().getInterfaces(), handler);
            proxy.doSomePost();
        }

        public void postEnhanceMethod(){
            InvocationHandler handler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("後置增強效果:");
                    Object res = method.invoke(service, args);
                    System.out.println("返回更新操作的結果,成功還是失敗?");
                    return res;
                }
            };
            IService proxy = (IService) Proxy.newProxyInstance(service.getClass().getClassLoader(),
                    service.getClass().getInterfaces(), handler);
            proxy.doSomePost();
        }
    }

    public static void main(String[] args) {
        EnhanceProxy proxy = new EnhanceProxy();
        proxy.preEnhanceMethod();
        System.out.println();
        proxy.postEnhanceMethod();
    }

}

運行結果如下:

前置增強效果:
檢查用戶是否有權限更新數據
提交表單更新數據

後置增強效果:
提交表單更新數據
返回更新操作的結果,成功還是失敗?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章