- 首先咆霜,派生MethodIntercepter接口,override intercept方法,在調(diào)用目標(biāo)類方法的前后加上額外的邏輯
- 其次席噩,使用Enhancer對(duì)象注冊(cè)目標(biāo)類和代理類,動(dòng)態(tài)生成代理對(duì)象
public class SomeBase{
public void someMethod(){
System.out.println("call SomeBase.someMethod");
}
}
public class SomeProxy implement MethodInterceptor{
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable{
System.out.println("Before calling SomeBase.someMethod");
proxy.invokeSuper(object, args);
System.out.println("After calling SomeBase.someMethod ");
}
}
public class Test{
public static void main(String[] args){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(SomeBase.class);
SomeProxy proxy = new SomeProxy();
enhancer.setCallback(proxy);
SomeBase base = (SomeBase)enhancer.create();
base.someMethod();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者