个人感觉,retrofit中的动态代理比较典型,我就拿出来解读一下:

先来阅读一下retrofit 的源码,看retrofit怎么来实现动态代理

ApiService apiService = retrofit.create(ApiService.class);

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, @Nullable 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这段代码主要作用是将类里的注解等参数解析,并包装成网络请求真正的数据,来进行请求数据。

咱模仿retrofit写一套动态代理:

定义注解:

@LeftFace
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited 
public @interface LeftFace {
    String value() default "左面脸";
}

 

@UpFace

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) 
@Inherited  
public @interface UpFace {
    String value() default "上面脸";
}
创建接口
public interface IFaceListener {

    @LeftFace
    String getFace(String name);

    @UpFace
    String getFacePoint(String name);
}

创建动态代理

public class FaceCreate {

    public <T> T create(final Class<T> face){
        return (T) Proxy.newProxyInstance(face.getClassLoader(), new Class<?>[]{face}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String result = null;
                if(method.isAnnotationPresent(LeftFace.class)){
                    LeftFace leftFace =  method.getAnnotation(LeftFace.class);
                    result = leftFace.value();
                }

                if(method.isAnnotationPresent(UpFace.class)){
                    UpFace upFace =  method.getAnnotation(UpFace.class);
                    result = upFace.value();
                }

                result = HString.concatObject(null,args)+result;
                return result;
            }
        });
    }

}

如此我们就模仿的建造了动态代理,动态代理在开发中相对与静态代理,灵活性更强。

解析 

new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) 


Object proxy:我们的真实对象
Method method:对象的方法 
Object[] args:对象的参数

Proxy.newProxyInstance(face.getClassLoader(), new Class<?>[]{face}, new InvocationHandler() {


ClassLoader loader:定义了由哪个ClassLoader对象来对生成的代理对象进行加载

Class<?>[] interfaces:一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了

InvocationHandler :InvocationHandler对象