在Java中,动态代理是一种设计模式,它允许我们在运行时动态地创建一个代理对象,用于拦截和处理对原始对象的方法调用。动态代理通常用于实现AOP(面向切面编程)、事务管理、日志记录等功能。
Java动态代理主要涉及到java.lang.reflect.Proxy
类和java.lang.reflect.InvocationHandler
接口。以下是动态代理的基本步骤:
public interface MyInterface {
void doSomething();
}
public class MyInterfaceImpl implements MyInterface {
@Override
public void doSomething() {
System.out.println("Doing something...");
}
}
InvocationHandler
实现类。这个类负责处理代理对象上的方法调用。import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method call...");
Object result = method.invoke(target, args);
System.out.println("After method call...");
return result;
}
}
Proxy.newProxyInstance()
方法创建代理对象。import java.lang.reflect.Proxy;
public class DynamicProxyDemo {
public static void main(String[] args) {
MyInterfaceImpl realObject = new MyInterfaceImpl();
MyInvocationHandler handler = new MyInvocationHandler(realObject);
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class<?>[]{MyInterface.class},
handler);
proxy.doSomething();
}
}
当我们调用代理对象的doSomething()
方法时,实际上会被MyInvocationHandler
中的invoke()
方法拦截。在invoke()
方法中,我们可以在调用原始对象的方法之前和之后执行自定义的操作,例如记录日志、性能监控等。
总结起来,动态代理允许我们在运行时动态地创建一个代理对象,用于拦截和处理对原始对象的方法调用。这种方式非常灵活,可以应用于许多场景,如AOP、事务管理等。