• Java动态代理


    Java动态代理是一种强大的机制,允许你在运行时创建一个实现了一组给定接口的代理类的实例。这个代理类可以用来拦截对原始对象的方法调用,执行额外的操作,比如日志记录、性能监控、事务处理等。下面是一个简单的Java动态代理的例子:

    定义接口

    首先,定义一个接口,代理类将实现这个接口的方法。

    public interface MyInterface {
        void performAction();
    }
    
    • 1
    • 2
    • 3

    实现类

    然后,创建一个实现此接口的类:

    public class MyInterfaceImpl implements MyInterface {
        @Override
        public void performAction() {
            System.out.println("Performing action in the original class");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    创建代理类

    接下来,创建一个实现InvocationHandler接口的类,用于定义方法调用的处理逻辑:

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class MyInvocationHandler implements InvocationHandler {
        private final MyInterface originalObject;
    
        public MyInvocationHandler(MyInterface originalObject) {
            this.originalObject = originalObject;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Before invoking " + method.getName());
            Object result = method.invoke(originalObject, args);
            System.out.println("After invoking " + method.getName());
            return result;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    使用动态代理

    最后,使用Proxy类创建代理实例并使用它:

    import java.lang.reflect.Proxy;
    
    public class ProxyExample {
        public static void main(String[] args) {
            MyInterface original = new MyInterfaceImpl();
            MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
                MyInterface.class.getClassLoader(),
                new Class[]{MyInterface.class},
                new MyInvocationHandler(original));
    
            proxy.performAction();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这个例子中,当你调用proxy.performAction()方法时,它会先打印“Before invoking performAction”,然后调用原始对象的performAction方法,最后打印“After invoking performAction”。这就是动态代理的基本用法,可以根据需要在调用原始方法之前或之后添加自定义的行为。

  • 相关阅读:
    Ubuntu自启动设置
    jQuery学习:多Tab实现点击切换
    隐马尔科夫模型(HMM)学习笔记
    数据结构之图(基本操作)
    智慧电网解决方案-最新全套文件
    关于接口|常见电商API接口种类|接口数据类型|接口请求方法
    数据库中间件-ShardingSphere-Proxy(一)
    springcloud五大组件:Eureka:注册中心、Zuul:服务网关、Ribbon:负载均衡、Feign:服务调用、Hystix:熔断器
    Sonatype Nexus: Recommended file descriptor limit is 65536 but count is 4096
    网络安全系列-四十五: DNS协议详细讲解
  • 原文地址:https://blog.csdn.net/weixin_43732424/article/details/134431262