Retrofit 动态代理+反射 基本原理

本文详细介绍了Retrofit在创建实例时如何利用动态代理生成接口的实现类,以及在方法调用时如何通过反射和Method对象来构建ServiceMethod并执行请求。核心过程包括:接口方法调用->动态代理invoke方法->反射获取Method对象->生成ServiceMethod->构建Call对象->适配器生成响应。
 retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
 httpbinService = retrofit.create(HttpbinService.class);
public <T> T create(final Class<T> service) {
    validateServiceInterface(service);
    return (T)
        Proxy.newProxyInstance(
            service.getClassLoader(),
            new Class<?>[] {service},
            new InvocationHandler() {
              private final Platform platform = Platform.get();
              private final Object[] emptyArgs = new Object[0];

              @Override
              public @Nullable 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);
                }
                args = args != null ? args : emptyArgs;
                return platform.isDefaultMethod(method)
                    ? platform.invokeDefaultMethod(method, service, proxy, args)
                    : loadServiceMethod(method).invoke(args);
              }
            });
  }

Retrofit动态代理会通过ClassLoader产生一个接口类型的.class文件,
这个文件中的成员方法在被调用的时候会回调动态代理中的invoke()方法,此方法中会携带Method类型的对象,通过反射可以将Method对象生成ServiceMethod对象,ServiceMethod对象中可以读取注解中的参数值,最终通过注解中的值构建一个Call对象,Call对象又通过不同的抽象工厂适配器生成不同的返回值对象。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值