動態(tài)代理其實就是java.lang.reflect.Proxy類動態(tài)的根據(jù)您指定的所有接口生成一個class在张,該class會繼承Proxy類,并實現(xiàn)所有你指定的接口(您在參數(shù)中傳入的接口數(shù)組);然后再利用您指定的classloader將class加載進系統(tǒng)亮航,最后生成這樣一個類的對象,并初始化該對象的一些值,如invocationHandler,以即所有的接口對應的Method成員睡毒。 初始化之后將對象返回給調用的客戶端。這樣客戶端拿到的就是一個實現(xiàn)你所有的接口的Proxy對象
- 業(yè)務接口類
public interface BusinessInterface {
public void processBusiness();
}
- 業(yè)務實現(xiàn)類
public class BusinessImpl implements BusinessInterface {
@override
public void processBusiness() {
System.out.println("執(zhí)行業(yè)務");
}
}
- 業(yè)務代理類
public BusinessProcessorHandler implements InvocationHandler {
private Object target冗栗;
public void setTarget(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throwsThrowable {
System.out.println("You can do something here before process your business");
Object result = method.invoke(target, args);
System.out.println("You can do something here after process your business");
return result;
}
}
- 具體應用類(關鍵代碼)
public static void main(String[] args) {
BusinessInterface bi = new BusinessImpl();
BusinessProcessorHandler handler = new BusinessProcessorHandler(bi);
BusinessInterface bp = (BusinessInterface) Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(),
bpimpl.getClass().getInterfaces(), handler);
bp.processBusiness();
}