根據(jù)上一個(gè)文章可輕松實(shí)現(xiàn)代理功能属韧,但是這樣做的代價(jià)是會(huì)生成許多的XxxProxy類亮钦,怎樣才能消除掉這些類呢掩完?這時(shí)我們可以使用JDK的動(dòng)態(tài)代理蟹地。
- 使用JDK提供的動(dòng)態(tài)代理方案
編寫(xiě)一個(gè)事務(wù)CarTimeHandler類 實(shí)現(xiàn)計(jì)時(shí)功能 、實(shí)現(xiàn)InvocationHandler接口
package cn.niriqiang.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by fengyuwusong on 2017/8/19 15:37.
*/
public class CarTimeHandler implements InvocationHandler {
//被代理的目標(biāo)對(duì)象
private Object target;
long start,end;
public CarTimeHandler(Object target) {
this.target = target;
}
private void before() {
start=System.currentTimeMillis();
System.out.println("開(kāi)車前時(shí)間:"+start);
}
private void after(){
end=System.currentTimeMillis();
System.out.println("開(kāi)車后時(shí)間:"+end+".\n總耗時(shí):"+(end-start)+"毫秒");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
method.invoke(target);
after();
return null;
}
}
再編寫(xiě)一個(gè)事務(wù)CarLogHandler類實(shí)現(xiàn)日志功能
package cn.niriqiang.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by fengyuwusong on 2017/8/19 23:58.
*/
public class CarLogHandler implements InvocationHandler {
ICar car;
public CarLogHandler(ICar car) {
this.car = car;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(car);
System.out.println("記錄日志");
return null;
}
}
則在main方法如此調(diào)用則可實(shí)現(xiàn)代理
package cn.niriqiang.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* Created by fengyuwusong on 2017/8/19 14:55.
*/
public class main {
public static void main(String[] args) {
// 靜態(tài)代理
// ICar car=new CarImpl();
// Carproxy carproxy=new Carproxy(car);
// CarLogProxy carLogProxy=new CarLogProxy(carproxy);
// carLogProxy.run();
// 動(dòng)態(tài)代理
ICar car=new CarImpl();
Class cls=car.getClass();
// 實(shí)現(xiàn)計(jì)時(shí)功能
InvocationHandler carTimeHandler=new CarTimeHandler(car);
car= (ICar) Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),carTimeHandler);
// 實(shí)現(xiàn)日志功能
InvocationHandler carLogHandler=new CarLogHandler(car);
car=(ICar)Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),carLogHandler);
car.run();
}
}
結(jié)果
開(kāi)車前時(shí)間:1503158582409
正在開(kāi)車~~~
開(kāi)車后時(shí)間:1503158583225.
總耗時(shí):816毫秒
記錄日志