Spring——模擬實現動態代理類
阿新 • • 發佈:2020-10-21
動態代理有兩種實現方式:
1. 基於介面實現動態代理:JDK動態代理
2. 基於繼承實現動態代理:Cglib、Javassist動態代理(尚且不會)
本文目標:動態代理一個計算器功能
第一步:建立介面 ArithmeticCalculator.java:
public interface ArithmeticCalculator {
public int add(int i, int j);
public int sub(int i, int j);
public int mul(int i, int j);
public int div(int i, int j);
}
第二步:建立要被代理的類的具體實現 ArithmeticCalculatorImpl.java:
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@Override
public int add(int i, int j) {
int result = i + j;
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
return result;
}
@Override
public int mul(int i, int j) {
int result = i * j;
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
return result;
}
}
第三步:生成代理物件:
ArithmeticCalculatorProxy.java
實現動態代理需要清楚三個問題:
目標物件;
如何獲取代理物件;
代理要做什麼
//目標物件
private ArithmeticCalculator target;
public ArithmeticCalculatorProxy(ArithmeticCalculator target) {
this.target = target;
}
獲取代理物件的方法:
在獲取代理物件時,採用的方法是呼叫Proxy類的newProxyInstance方法:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
ClassLoader loader = target.getClass().getClassLoader();
Class[] interfaces = target.getClass().getInterfaces();
InvocationHandler h的實現為匿名內部類:
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
//記錄日誌
System.out.println("LoggingProxy==> The method " + methodName + " begin with "+ Arrays.asList(args));
Object result = method.invoke(target, args); //目標物件執行目標方法。相當於執行ArithmeticCalculatorImpl中的+-*/
//記錄日誌
System.out.println("LoggingProxy==> The method " + methodName + " ends with "+ result);
return result;
}
}
測試函式:
執行結果: