动态代理

81 阅读1分钟

声明接口和实现类

interface IAnimal {
    void run();
}
public class Bird implements IAnimal {
    @Override
    public void run() {
        System.out.println("bird fly");
    }
}

静态代理

静态代理简单事件

public class AnimalProxy implements IAnimal {
    IAnimal trueAnimal;
    AnimalProxy(IAnimal trueAnimal) {
        this.trueAnimal = trueAnimal;
    }
    @Override
    public void run() {
        System.out.println("do something before run");
        trueAnimal.run();
        System.out.println("do something after run");
    }
}

new AnimalProxy(new Bird()).run();
// do something before run
// bird fly
// do something after run

动态代理

需要实现 java.lang.reflect.InvocationHandler

import java.lang.reflect.Method;

public class InvocationHandler<T> implements java.lang.reflect.InvocationHandler {
    private final T target;
    public InvocationHandler(T target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        StringBuilder params = new StringBuilder();
        if (args != null) {
            for (Object arg : args) {
                params.append(arg.toString());
            }
        }
        System.out.println("proxy do before true method:" + method.getName() + "  params:" + params);
        Object result = method.invoke(target, args);
        System.out.println("proxy do after true method:" + method.getName());
        return result;
    }
}

// 创建IAnimal动态代理并执行
try {
    Bird extension = new Bird();
    InvocationHandler<Bird> handler = new InvocationHandler<>(extension);
    IAnimal executor = (IAnimal) Proxy.newProxyInstance(IAnimal.class.getClassLoader(), new Class<?>[]{IAnimal.class}, handler);
    executor.run();
} catch (Exception e) {
    e.printStackTrace();
}
// proxy do before true method:run  params:
// bird fly
// proxy do after true method:run

延伸(retrofit动态代理)

retrofit2.Retrofit

public <T> T create(final Class<T> service) {
  Utils.validateServiceInterface(service);
  if (validateEagerly) {
    eagerlyValidateMethods(service);
  }
  return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
      new InvocationHandler() {
        private final Platform platform = Platform.get();

        @Override public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
          // If the method is a method from Object then defer to normal invocation.
          if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args);
          }
          if (platform.isDefaultMethod(method)) {
            return platform.invokeDefaultMethod(method, service, proxy, args);
          }
          ServiceMethod<Object, Object> serviceMethod =
              (ServiceMethod<Object, Object>) loadServiceMethod(method);
          OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
          return serviceMethod.callAdapter.adapt(okHttpCall);
        }
      });
}

retrofit 创建了用户声明的service动态代理,并未真正使用service代理类,只是利用其声明(注解)取用户定义的接口路径、参数等