使用 cglib 把实例包装后,捕获对实例方法的调用
使用 cglib 把一个类或者实例进行包装的例子。
import java.lang.reflect.Method;
import net.sf.cglib.proxy.*;
public class Wrapper implements MethodInterceptor {
/**
* Target object to be wrapped
*/
private Object target = null;
public static Object wrap(Class clazz) {
try{
Wrapper interceptor = new Wrapper();
Enhancer e = new Enhancer ();
e.setSuperclass(clazz);
e.setCallback (interceptor);
Object obj = e.create();
return obj;
}catch( Throwable e ){
e.printStackTrace();
throw new Error(e.getMessage());
}
}
public static Object wrap(Object obj) {
try{
Wrapper interceptor = new Wrapper();
Enhancer e = new Enhancer ();
e.setSuperclass(obj.getClass());
e.setCallback (interceptor);
interceptor.target = obj ;
return e.create();
}catch( Throwable e ){
e.printStackTrace();
throw new Error(e.getMessage());
}
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
if( target != null ) {
System.out.println("Invoked: " + method.getName());
return method.invoke(target, args);
}
else {
return proxy.invokeSuper(obj, args);
}
}
}