Java的动态代理是一种在运行时动态生成代理对象的机制。动态代理可以在不修改原始类代码的情况下,为目标对象添加额外的功能或拦截方法调用。Java提供了java.lang.reflect.Proxy类来支持动态代理。
要实现Java的动态代理,需要完成以下步骤:
定义一个接口:目标对象需要实现的接口。动态代理对象将实现这个接口,以便它可以代理目标对象的方法调用。
public interface MyInterface {
void myMethod();
}
创建目标对象:创建一个实现上述接口的类,这将是代理对象的目标对象。
public class MyTarget implements MyInterface {
@Override
public void myMethod() {
System.out.println("Target method is called.");
}
}
实现InvocationHandler接口:创建一个实现java.lang.reflect.InvocationHandler接口的类。这个类将处理代理对象的方法调用。
public class MyInvocationHandler implements InvocationHandler {
private final MyInterface target;
public MyInvocationHandler(MyInterface 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;
}
}
在上面的示例中,MyInvocationHandler实现了InvocationHandler接口,并在invoke方法中添加了方法调用前后的日志。
创建动态代理对象:使用Proxy.newProxyInstance()方法创建动态代理对象。这个方法需要一个类加载器、一个接口数组和一个实现了InvocationHandler接口的对象作为参数。
MyInterface target = new MyTarget();
InvocationHandler handler = new MyInvocationHandler(target);
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[]{MyInterface.class}, handler);
现在,proxy对象是MyInterface的一个实现,它会将方法调用转发给MyInvocationHandler的invoke方法。当调用proxy.myMethod()时,将输出Before method call.、Target method is called.和After method call.。
这就是Java动态代理的实现过程。通过使用动态代理,我们可以在不修改原始类代码的情况下,为目标对象添加额外的功能或拦截方法调用,这在很多框架和库中都有广泛应用,如Spring AOP等。