本身寫的一個 CGBLIB 動態代理【原創】

CGLIB代理類,用CGLIB來實現一個代理類。大體原理描述以下:java

一、使用Enhancer類來生成一個繼續於被代理類的子類,此子類會重寫被代理類(父類)中全部的非final的public方法;ide

二、當調用代理類的某個方法時實際上經過一個MethodInterceptor委託來間接調用的;測試

三、MethodInterceptor的intercept方法會對被代理類的方法進行加強(加強的邏輯是經過Interceptor接口來實現的)並調用被代理類(super class)的相關方法。ui

調用過程以下圖:spa

CglibProxy類實現核心代理邏輯,並提供一個Interceptor接口供客戶端來實現加強邏輯。代理

package proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * @author xfyou
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class CglibProxy<T> {

  private final Class<T> targetClass;
  private final MethodInterceptor methodInterceptor;

  public static <T> CglibProxy<T> newInstance(Class<T> targetClass, Interceptor interceptor) {
    return new CglibProxy<>(targetClass, new MethodInterceptor() {
      @Override
      public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        interceptor.before(obj);
        Object invokeResult;
        try {
          invokeResult = proxy.invokeSuper(obj, args);
        } catch (Throwable e) {
          interceptor.exception(obj, e);
          throw new InvocationTargetException(e);
        }
        interceptor.after(obj);
        return invokeResult;
      }
    });
  }

  @SuppressWarnings("unchecked")
  public T createNewObj() {
    return (T) createNewEnhancer().create();
  }

  private Enhancer createNewEnhancer() {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setCallback(methodInterceptor);
    return enhancer;
  }

  public interface Interceptor {

    /**
     * Do something before invoke the super class method
     *
     * @param obj Instances of proxied objects
     */
    void before(Object obj);

    /**
     * Do something after invoked the super class method
     *
     * @param obj Instances of proxied objects
     */
    void after(Object obj);

    /**
     * Do something when exception occurred when invoke the super class method
     *
     * @param obj Instances of proxied objects
     * @param e Exception
     */
    void exception(Object obj, Throwable e);

  }

}

 WorkProxy類用來對Work類進行代理,生成的是一個單例的代理類。code

package proxy;

import proxy.CglibProxy.Interceptor;

/**
 * @author xfyou
 * @date 2019/10/15
 */
public class WorkProxy {

  private static Work proxyObject;

  private static Interceptor interceptor = new Interceptor() {

    @Override
    public void before(Object obj) {
      System.out.println("before");
    }

    @Override
    public void after(Object obj) {
      System.out.println("after");
    }

    @Override
    public void exception(Object obj, Throwable e) {
      System.out.println("exception");
    }

  };

  static {
    proxyObject = CglibProxy.newInstance(Work.class, interceptor).createNewObj();
  }

  public static Work get() {
    return proxyObject;
  }

}

被代理的Work類以下:blog

package proxy;

/**
 * Work
 */
public class Work {

    public void doWork() {
        System.out.println("Do work");
    }

}

測試代碼:接口

package proxy;

/**
 * @author xfyou
 * @date 2019/10/15
 */
public class Test {

  public static void main(String[] args) {
    WorkProxy.get().doWork();
  }

}
相關文章
相關標籤/搜索