动态代理是Java中一种强大的机制,可以在运行时创建代理类和对象。通过使用JDK动态代理,你可以实现在目标类的方法执行前后进行不同的增强操作。
首先,定义一个接口,该接口包含你想要代理的方法:
public interface MyInterface {
void method1();
String method2(String input);
}
然后,创建一个实现该接口的目标类:
public class MyTargetClass implements MyInterface {
@Override
public void method1() {
System.out.println("Executing method1");
}
@Override
public String method2(String input) {
System.out.println("Executing method2 with input: " + input);
return "Output from method2";
}
}
接下来,创建一个实现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;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在方法执行前的增强操作
System.out.println("Before executing method: " + method.getName());
// 调用目标对象的方法
Object result = method.invoke(target, args);
// 在方法执行后的增强操作
System.out.println("After executing method: " + method.getName());
return result;
}
}
最后,创建一个测试类,使用Proxy.newProxyInstance
方法创建代理对象并调用方法:
import java.lang.reflect.Proxy;
public class ProxyExample {
public static void main(String[] args) {
// 创建目标对象
MyInterface target = new MyTargetClass();
// 创建InvocationHandler实例
MyInvocationHandler handler = new MyInvocationHandler(target);
// 创建代理对象
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class[]{MyInterface.class},
handler
);
// 调用代理对象的方法
proxy.method1();
String result = proxy.method2("Hello");
System.out.println("Result from method2: " + result);
}
}
在上述例子中,MyInvocationHandler
类中的invoke
方法定义了在方法执行前和执行后的增强操作。