主要步骤
- 定义接口:定义需要代理的接口,如
SomeInterface
,包含需要代理的方法,例如doSomething()
。
- 实现InvocationHandler接口:创建一个类实现
InvocationHandler
接口,在invoke
方法中编写代理逻辑,该方法接收目标对象、方法对象以及方法参数作为参数。
- 使用Proxy类创建代理实例:通过
Proxy.newProxyInstance
方法创建代理实例,该方法需要传入类加载器、目标接口数组以及InvocationHandler
实例。
示例代码
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface SomeInterface {
void doSomething();
}
class SomeInterfaceImpl implements SomeInterface {
@Override
public void doSomething() {
System.out.println("实际方法执行");
}
}
class ProxyHandler implements InvocationHandler {
private Object target;
public ProxyHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理逻辑前置处理");
Object result = method.invoke(target, args);
System.out.println("代理逻辑后置处理");
return result;
}
}
public class ProxyExample {
public static void main(String[] args) {
SomeInterface target = new SomeInterfaceImpl();
InvocationHandler handler = new ProxyHandler(target);
SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
handler);
proxy.doSomething();
}
}