標籤:
/**
* 動態產生一個代理類對象,並綁定被代理類和代理處理器
*
* @param business
* @return 代理類對象
*/
public Object bind(Object business) {
this.business = business;
return Proxy.newProxyInstance(
//被代理類 的ClassLoader
business.getClass().getClassLoader(),
//要被代理 的介面,本方法返回對象會自動聲稱實現了這些介面
business.getClass().getInterfaces(),
//代理處理 器對象
this);
}
/**
* 代理要調用的方法,並在方法調用前後調用連接器的方法.
*
* @param proxy 代理類對象
* @param method 被代理的介面方法
* @param args 被代理介面方法的參數
* @return 方法調用返回的結果
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
interceptor.before();
result=method.invoke(business,args);
interceptor.after();
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
三、攔截器:普通的JavaBean,在調用業務方法的之前或者之後會自動攔截並執行自己的 一些方法。
/**
* 攔截器
*/
public class InterceptorClass {
public void before(){
System.out.println("攔截器InterceptorClass方法調用:before()!");
}
public void after(){
System.out.println("攔截器InterceptorClass方法調用:after()!");
}
}
四、類比用戶端:執行業務處理的入口。
/**
* 用戶端
*/
public class Client {
public static void main(String args[]) {
DynamicProxyHandler handler = new DynamicProxyHandler();
BusinessInterface business = new BusinessClass();
BusinessInterface businessProxy = (BusinessInterface) handler.bind(business);
businessProxy.doSomething();
}
}
Java實現的攔截器