在Java中,动态代理可以通过实现java.lang.reflect.InvocationHandler
接口来创建。下面是一个简单的示例,演示如何使用JDK动态代理:
首先,定义一个接口,代理类将实现这个接口的方法:
public interface MyInterface {void doSomething();
}
然后,创建InvocationHandler
的实现,这将定义代理对象的调用行为:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class MyInvocationHandler implements InvocationHandler {private final Object target; // 被代理的对象public MyInvocationHandler(Object target) {this.target = target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 在转发请求前可以进行一些处理System.out.println("Before method " + method.getName());// 转发调用到真实对象的方法Object result = method.invoke(target, args);// 在转发请求后可以进行一些处理System.out.println("After method " + method.getName());return result;}
}
最后,使用java.lang.reflect.Proxy
类来动态创建代理对象:
import java.lang.reflect.Proxy;public class DynamicProxyExample {public static void main(String[] args) {// 创建被代理的实例对象MyInterface realObject = new MyInterface() {@Overridepublic void doSomething() {System.out.println("Doing something...");}};// 创建InvocationHandler,并传入被代理的对象MyInvocationHandler handler = new MyInvocationHandler(realObject);// 创建代理对象MyInterface proxyInstance = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(),new Class<?>[] {MyInterface.class},handler);// 通过代理对象调用方法proxyInstance.doSomething();}
}
在这个例子中,Proxy.newProxyInstance
方法接收三个参数:
- 类加载器(class loader)用来定义代理类。
- 一个要实现的接口数组,代理类将实现这些接口。
InvocationHandler
实例来处理方法调用。
当你通过代理对象调用方法时,它会被转发到InvocationHandler
的invoke
方法。在invoke
方法中,你可以在调用真实对象之前或之后添加自己的逻辑。上述代码运行时,代理将会在实际执行doSomething
方法之前后打印信息。