- JDK动态代理是基于接口的动态代理,是否觉得为每一个类编写InvocationHandler感到烦恼
假如能提供一个工厂,只需要传一个类名就能实现,岂不美哉
public interface Actions {
/**
* 定义是否重写被代理类方法
* */
boolean isOver();
}
//覆盖原方法
public abstract class OverAction<T> implements Actions {
@Override
public boolean isOver() {
return true;
}
//重写方法
public abstract T overWrite(Object[] args);
}
//前置增强及后置增强
public abstract class ProxyActions implements Actions {
@Override
public boolean isOver() {
return false;
}
/**
* 前置增强
* */
public abstract Object[] doBefore(Object[] args);
/**
* 后置增强
* */
public abstract Object doAfter(Object result);
}
生成代理类(匿名内部类),不用再为每个类方法写一个集成InvocationHandler
//代理工厂
public class ProxyFactory<T> {
public T getInstance(Class<?> proxyClass, Actions action) {
return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(),
proxyClass.getInterfaces(),
(proxy, method, args) -> {
if (action.isOver()) {
return ((OverAction) action).overWrite(args);
} else {
ProxyActions proxyActions = (ProxyActions) action;
Object[] beforeResult = proxyActions.doBefore(args);
Object invoke = method.invoke(proxyClass.newInstance(), beforeResult);
proxyActions.doAfter(invoke);
return invoke;
}
});
}
}
接口类及其实现方法
public interface RecordService {
String record(String content,Integer number);
}
public class RecordServiceImpl implements RecordService {
@Override
public String record(String content, Integer number) {
System.out.println("原方法执行.....");
return "123";
}
}
测试:
public class StartProxy {
public static void main(String[] args) {
RecordService recordProxyAction = new ProxyFactory<RecordService>().getInstance(RecordServiceImpl.class,
new ProxyActions() {
@Override
public Object[] doBefore(Object[] args) {
System.out.println("doBefore......");
return args;
}
@Override
public Object doAfter(Object result) {
System.out.println("doAfter......");
return "doAfter";
}
});
String result = recordProxyAction.record("good job", 123);
System.out.println("最终结果" + result);
RecordService instance1 = new ProxyFactory<RecordService>().getInstance(RecordServiceImpl.class,
new OverAction<String>() {
@Override
public String overWrite(Object[] args) {
System.out.println("overWrite......");
return "473890743";
}
});
String record = instance1.record("123", 456);
System.out.println("最终结果" + record);
}
}