Java动态代理

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

定义接口

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

public interface MyInterface {
    void performAction();
}

实现类

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

public class MyInterfaceImpl implements MyInterface {
    @Override
    public void performAction() {
        System.out.println("Performing action in the original class");
    }
}

创建代理类

接下来,创建一个实现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;
    }
}

使用动态代理

最后,使用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();
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值