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-------

原文地址:https://www.cnblogs.com/jigang/p/12950966.html