- 首先,派生MethodIntercepter接口,override intercept方法,在调用目标类方法的前后加上额外的逻辑
- 其次,使用Enhancer对象注册目标类和代理类,动态生成代理对象
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();
}
}
网友评论