1. 定义接口
首先,我们需要定义一个接口,代理对象将实现这个接口。
/**
* @author linqinyong
* @version 1.0.0
* @ClassName ExampleInterface.java
* @Description
* @createTime 2025年02月28日 13:11:00
*/
public interface ExampleInterface {
String doSomething(String param);
}
2. 实现接口
创建一个类来实现上述定义的接口。
/**
* @author linqinyong
* @version 1.0.0
* @ClassName ExampleService.java
* @Description
* @createTime 2025年02月28日 13:23:00
*/
public class ExampleService implements ExampleInterface{
@Override
public String doSomething(String param) {
return "param";
}
}
3. 创建代理处理器
代理处理器是实现 InvocationHandler 接口的类,它负责处理代理对象的方法调用。
/**
* @author linqinyong
* @version 1.0.0
* @ClassName MyInvocationHandler.java
* @Description
* @createTime 2025年02月28日 13:19:00
*/
public class MyInvocationHandler<T> implements InvocationHandler {
private T target;
public MyInvocationHandler(T target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在调用目标方法之前,可以进行一些预处理操作
System.out.println("Before method call: " + method.getName());
// 调用目标对象的方法
Object result = method.invoke(target, args);
// 在调用目标方法之后,可以进行一些后处理操作
System.out.println("After method call: " + method.getName());
return result;
}
}
5. 创建代理
/**
* @author linqinyong
* @version 1.0.0
* @ClassName MyProxyFactory.java
* @Description
* @createTime 2025年02月28日 13:13:00
*/
public class MyProxyFactory {
public static <T> T getProxy(T target) {
// 获取目标对象的类加载器
ClassLoader classLoader = target.getClass().getClassLoader();
// 获取目标对象实现的所有接口
Class<?>[] interfaces = target.getClass().getInterfaces();
// 创建代理处理器
MyInvocationHandler<T> targetMyInvocationHandler = new MyInvocationHandler<>(target);
// 使用 Proxy.newProxyInstance 方法创建代理对象
Object o = Proxy.newProxyInstance(classLoader, interfaces, targetMyInvocationHandler);
return (T) o;
}
}
5. 测试代码
创建一个测试类来演示如何使用 JDK 动态代理。
/**
* @author linqinyong
* @version 1.0.0
* @ClassName ProxyTest01.java
* @Description
* @createTime 2025年02月28日 13:12:00
*/
public class ProxyTest01 {
public static void main(String[] args) {
ExampleService exampleService = new ExampleService();
// 使用通用代理工厂创建代理对象
ExampleInterface proxyObject= MyProxyFactory.getProxy(exampleService);
// 调用代理对象的方法
proxyObject.doSomething("1111");
}
}
收起