• 动态代理 Proxy InvocationHandler


    能够在核心业务方法前后做一些你所想做的辅助工作,如log日志,安全机制等等。

    import java.lang.reflect.*;

    public interface Business{public void do();}

    public class BusinessImp implements Business{public void do(){。。。}}

    public class MyInvocationHandler implements InvocationHandler{

      private Object target = null;

      public MyInvocationHandler(Object target){this.target = target;}

    @Override

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{

        调用核心业务方法前操作

        Object result = method.invoke(target, args);

        调用核心业务方法后操作

        return result;//返回代理对象

      }

    }

    public class Test{

      BusinessImp busi = new BusinessImp();//被代理对象

      MyInvocationHandler handler = new MyInvocationHandler(busi);

      Business proxy = (Business)Proxy.newProxyInstance(busi.getClass().getClassLoader(), busi.getClass().getInterface(),handler);

      proxy.do();//调用do时会调用handler的invoke方法

    }

  • 相关阅读:
    ultraedit 窗口布局
    Oracle之Char VarChar VarChar2
    Python之pickle
    Python之xpath
    Python常用数据结构之heapq模块
    Python实现排序算法之快速排序
    Python常用数据结构之collections模块
    New York is 3 hours ahead of California
    leetcode978
    leetcode979
  • 原文地址:https://www.cnblogs.com/zawjdbb/p/7444550.html
Copyright © 2020-2023  润新知