1.接口
public interface UserService {
JSONObject getUser();
}
实现
public class UserServiceImpl implements UserService {
@Override
public JSONObject getUser() {
JSONObject object = new JSONObject();
object.put("name", "meikb");
return object;
}
}
2.代理类
public class CglibProxy implements MethodInterceptor {
private Object object;
public CglibProxy(Object object){
this.object = object;
}
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println(method.getName() + "方法被调用");
Object result = method.invoke(object, args);
System.out.println( "结果" + result.toString());
System.out.println(method.getName() + "调用完成");
return result;
}
public Object getCglibProxy(){
return new Enhancer().create(object.getClass(), this);
}
}
参数当然可以传入接口,参考JDK动态代理。
3.使用
public class UserMain {
public static void main(String[] args) {
CglibProxy cglibProxy = new CglibProxy(new UserServiceImpl());
UserService proxy = (UserService)cglibProxy.getCglibProxy();
proxy.getUser();
}
}
4.原理
调用 Enhancer.createHelper 类
private Object createHelper() {
this.validate();
if (this.superclass != null) {
this.setNamePrefix(this.superclass.getName());
} else if (this.interfaces != null) {
this.setNamePrefix(this.interfaces[ReflectUtils.findPackageProtected(this.interfaces)].getName());
}
return super.create(KEY_FACTORY.newInstance(this.superclass != null ? this.superclass.getName() : null, ReflectUtils.getNames(this.interfaces), this.filter, this.callbackTypes, this.useFactory, this.interceptDuringConstruction, this.serialVersionUID));
}
TODO Enhancer