不像JDK代理一样打印,代理前->执行代理对象->代理后;
而是代理对象执行随机好像。
class People{
void hello(String arg) {
System.out.println(arg);
}
}
public class CglibProxy implements MethodInterceptor {
public Object getProxy(Class cls) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(cls);
enhancer.setCallback(this);
return enhancer.create();
}
/***
*
* 为什么这个动态代理奇怪在它的打印顺序是随机的。不保序;
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.err.println("say it for always");
Object result = methodProxy.invokeSuper(proxy, args);
System.err.println("say it together");
return result;
}
public static void main(String[] args) {
CglibProxy cp = new CglibProxy();
People obj = (People)cp.getProxy(People.class);
obj.hello("And what they played was a masquerade");
}
}