spring动态代理

柔情只为你懂 2022-11-07 11:41 223阅读 0赞

1.实现方法

  1. package com.zhu.Proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. //实现InvocationHandler接口
  6. public class ProxyInvocationHandler implements InvocationHandler {
  7. // 定义一个Object类的变量。
  8. private Object target;
  9. public void setTarget(Object target) {
  10. this.target = target;
  11. }
  12. public Object getProxy(){
  13. // this.getClass().getClassLoader() :本类的类加载器
  14. // target.getClass().getInterfaces():目标类的接口
  15. // this:调用处理程序(也就是本类)
  16. return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
  17. }
  18. // 处理代理对象,并返回结果
  19. @Override
  20. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  21. Object result = method.invoke(target,args);
  22. return result;
  23. }
  24. }

2.测试代码

  1. package com.zhu.Proxy;
  2. import com.zhu.pojo.Student;
  3. import com.zhu.pojo.StudentImpl;
  4. public class Test {
  5. public static void main(String[] args){
  6. // 创建一个真实对象
  7. StudentImpl student = new StudentImpl();
  8. // 生成一个代理对象
  9. ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
  10. proxyInvocationHandler.setTarget(student);
  11. Student student1 = (Student) proxyInvocationHandler.getProxy();
  12. // 执行方法
  13. student1.put();
  14. }
  15. }

提示;

proxy有一个方法(newProxyInstance)可以创建一个代理对象。参数是,该类的类加载器,和被代理的接口,和调用处理程序。

invoke方法是处理代理实例,并且返回结果的。

在这里插入图片描述

每一个代理实例都有一个调用处理程序

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读

    相关 spring 03.动态代理

    概述:   动态代理是指动态的在内存中构建代理对象(需要我们制定要代理的目标对象实现的接口类型),即利用JDK的API生成指定接口的对象,也称之为JDK代理或者接口代理。