- 首先,派生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();
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。