概念
一种常用的涉及模式,为其他对象提供一个代理以控制对某个对象的访问。原方法可以不变,可加入自己的增强逻辑
使用案例
package service;
/**
* 动态代理的接口
*/
public interface ProxyService {
public int testProxy();
}
package service.impl;
import service.ProxyService;
/**
* 需要代理的实际对象
*/
public class ProxyServiceImpl implements ProxyService {
@Override
public int testProxy() {
return 1;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* 处理器
*/
public class MyProxyHandler implements InvocationHandler {
// 增强对象
private Object target;
public MyProxyHandler(Object target) {
this.target = target;
}
/**
* @param proxy 代理类实例
* @param method 被调用的方法对象
* @param args 调用参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("===========方法开始===========");
Object invoke = method.invoke(target, args);
// 增强逻辑
if (Objects.nonNull(invoke)){
Integer num = (Integer)invoke;
invoke = num *10;
}
System.out.println("===========方法结束===========");
return invoke;
}
}
import service.ProxyService;
import service.impl.ProxyServiceImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class MyProxyTest {
public static void main(String[] args) {
ProxyServiceImpl proxyService = new ProxyServiceImpl();
/**
* MyProxyHandler 实现了 InvocationHandler 接口,并能实现方法调用从代理类到委托类的分派转发
* 其内部通常包含指向委托类实例的引用,用于真正执行分派转发过来的方法调用.
* 即:要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法
*/
InvocationHandler invocationHandler = new MyProxyHandler(proxyService);
/**
* 该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例
*/
ProxyService proxy = (ProxyService)Proxy.newProxyInstance(proxyService.getClass().getClassLoader(),
proxyService.getClass().getInterfaces(),
invocationHandler);
System.out.println(proxy.testProxy());
}
}
总结
- 通过实现 InvocationHandler 接口创建自己的调用处理器;
- 通过为 Proxy 类指定 ClassLoader 对象和一组 interface 来创建动态代理类;
- 通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型;
- 通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。