- 前言
- 二、具体代码
- 1.定义接口IProduct
- 2.定义实现类Product
- 3.定义抽象调用处理器
- 4.定义调用实际处理器实现类
- 5.定义jdk动态代理工厂
- 客户端调用
- 总结
前言
二、具体代码 1.定义接口IProductJDK中的动态代理是通过反射类Proxy以及InvocationHandler回调接口实现的;
JDK中所要进行动态代理的类必须要实现一个接口
需求:
计算一个类中,每个被调用的方法运行时长
package design.patterns.proxy;
public interface IProduct {
String sell(Float money);
void afterSell();
}
2.定义实现类Product
package design.patterns.proxy;
import java.util.concurrent.TimeUnit;
public class Product implements IProduct {
@Override
public String sell(Float money) {
System.out.println("代理员交给工厂:" + money);
return "aaa";
}
@Override
public void afterSell() {
System.out.println("代理员做售后。。等待5秒");
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception ignore) {
}
}
}
3.定义抽象调用处理器
package design.patterns.proxy; import java.lang.reflect.InvocationHandler; public abstract class MyHandler4.定义调用实际处理器实现类implements InvocationHandler { protected T targetInstance; public MyHandler(T targetInstance) { this.targetInstance = targetInstance; } public T getTargetInstance() { return targetInstance; } }
动态计算方法运行时长
package design.patterns.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class CalcTimeHandler5.定义jdk动态代理工厂extends MyHandler implements InvocationHandler { public CalcTimeHandler(T targetInstance) { super(targetInstance); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //这些方法不进行增强处理控制 //边界判断 if ("equals getClass hashCode toString wait notifyAll".contains(method.getName())) { return method.invoke(targetInstance, args); } long startTime = System.currentTimeMillis(); Object invoke = method.invoke(targetInstance, args); long end = System.currentTimeMillis(); System.out.format("%s方法执行时间:%s毫秒%n", method.getName(), end - startTime); return invoke; } }
该静态工厂使用的是泛型类
package design.patterns.proxy;
import design.patterns.decorate.CalcTimeHandler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class MyJdkProxyFactory {
private static T getProxy(Class>[] interfaces, InvocationHandler handler) {
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, handler);
}
private static T getProxy(MyHandler handler) {
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), handler.getTargetInstance().getClass().getInterfaces(), handler);
}
private static T getProxy2(MyHandler handler) {
return (T) Proxy.newProxyInstance(handler.getClass().getClassLoader(), handler.getTargetInstance().getClass().getInterfaces(), handler);
}
}
客户端调用
public static void main(String[] args) {
IProduct product = new Product();
IProduct productProxy = MyJdkProxyFactory.getProxy(new CalcTimeHandler<>(product));
//无感地对代码进行了动态的增强控制
//调用代理实例的方法对原实例进行动态增强
System.out.println(productProxy.sell(3f));
productProxy.afterSell();
System.out.println(productProxy.hashCode());
System.out.println(product.hashCode());
}
总结
提示:这里对文章进行总结:
在不改变原有代码的基础上对代理对象的方法进行了动态的增强
核心代码逻辑:对代理对象的每个方法进行计算方法调用运行时长



