1.接口

  1. public interface UserService {
  2. JSONObject getUser();
  3. }

实现

  1. public class UserServiceImpl implements UserService {
  2. @Override
  3. public JSONObject getUser() {
  4. JSONObject object = new JSONObject();
  5. object.put("name", "meikb");
  6. return object;
  7. }
  8. }

2.代理类

  1. public class CglibProxy implements MethodInterceptor {
  2. private Object object;
  3. public CglibProxy(Object object){
  4. this.object = object;
  5. }
  6. @Override
  7. public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
  8. System.out.println(method.getName() + "方法被调用");
  9. Object result = method.invoke(object, args);
  10. System.out.println( "结果" + result.toString());
  11. System.out.println(method.getName() + "调用完成");
  12. return result;
  13. }
  14. public Object getCglibProxy(){
  15. return new Enhancer().create(object.getClass(), this);
  16. }
  17. }

参数当然可以传入接口,参考JDK动态代理。

3.使用

  1. public class UserMain {
  2. public static void main(String[] args) {
  3. CglibProxy cglibProxy = new CglibProxy(new UserServiceImpl());
  4. UserService proxy = (UserService)cglibProxy.getCglibProxy();
  5. proxy.getUser();
  6. }
  7. }

4.原理

调用 Enhancer.createHelper 类

  1. private Object createHelper() {
  2. this.validate();
  3. if (this.superclass != null) {
  4. this.setNamePrefix(this.superclass.getName());
  5. } else if (this.interfaces != null) {
  6. this.setNamePrefix(this.interfaces[ReflectUtils.findPackageProtected(this.interfaces)].getName());
  7. }
  8. 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));
  9. }

TODO Enhancer