静态代理->装饰器模式

jdk动态代理

运行的时候动态生成代理类
被代理类必须实现接口

cglib

  1. /**
  2. * CGLIB实现动态代理不需要接口,底层是asm
  3. */
  4. public class Main {
  5. public static void main(String[] args) {
  6. Enhancer enhancer = new Enhancer();
  7. enhancer.setSuperclass(Tank.class);
  8. enhancer.setCallback(new TimeMethodInterceptor());
  9. Tank tank = (Tank)enhancer.create();
  10. tank.move();
  11. }
  12. }
  13. class TimeMethodInterceptor implements MethodInterceptor {
  14. @Override
  15. public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
  16. System.out.println(o.getClass().getSuperclass().getName());
  17. System.out.println("before");
  18. Object result = null;
  19. result = methodProxy.invokeSuper(o, objects);
  20. System.out.println("after");
  21. return result;
  22. }
  23. }
  24. class Tank {
  25. public void move() {
  26. System.out.println("Tank moving claclacla...");
  27. try {
  28. Thread.sleep(new Random().nextInt(10000));
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

asm

修改class二进制码