zoukankan      html  css  js  c++  java
  • JDK动态代理

    Spring的AOP实现用了Proxy和InvocationHandler,现在就介绍一下JDK动态代理。

    自定义的InvocationHandler需要重写3个函数。

      1)构造函数,将代理对象传入

      2)invoke方法

      3)getProxy方法

    1、创建业务接口

    public interface UserService{

      public void add();

    }

    2、创建业务接口实现类

    public class UserServiceImpl implements UserService{

      public void add(){

        System.out.println("-----add-----");

      }

    }

    3、创建自定义的InvocationHandler

    public class MyInvocationHandler implements InvocationHandler{

      //目标对象

      private Object target;

      public MyInvocationHandler(Object target){

        super();

        this.target=target;

      }

    4、执行目标对象的方法

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

        System.out.println("-----before-----");

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

        System.out.println("----after-----");

      }

    5、获取目标对象的代理对象

    public Object getProxy(){

      return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.Class.getInstance(),this);

      }

    }

    6、测试代理

    public class ProxyTest{

    @Test

    public void testProxy()throws Throwable{

      //实例化目标对象

      UserService userService=new UserServiceImpl();

      //实例化InvocationHandler

      MyInvocaitonHanlder invovationHandler=new MyInvocationHandler(userService);

      //根据目标对象生成代理对象

      UserService proxy=(UserService) invocationHandler.getProxy();

      //调用代理对象的方法

      proxy.add();

      }

    }

    7、测试结果

    ------before------

    ------add--------

    ------after-------

  • 相关阅读:
    无法通过给定的扩展名确定设备类型
    biuld example_osgviewerGLUT遇到的error Link2019
    OpenGL渲染流水线
    设计模式总目录
    删除thumbs.db是提示正在使用
    COM技术内幕第十章笔记EXE中的服务器
    在高低版本之间互导max文件,以fbx格式为载体尤佳。
    参数值传递的本质
    VS 为什么要检查行尾的一致性?
    vs2005中的GL文件
  • 原文地址:https://www.cnblogs.com/jigang/p/12950966.html
Copyright © 2011-2022 走看看