Builder(Platform platform) { this.platform = platform; // Add the built-in converter factory first. This prevents overriding its behavior but also // ensures correct behavior when using converters that consume all types. converterFactories.add(new BuiltInConverters()); }
// Make a defensive copy(备份) of the adapters and add the default Call adapter. List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters. List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
public <T> T create(final Class<T> service){ Utils.validateServiceInterface(service);//判断service是否为接口类,以及该接口是否有继承 if (validateEagerly) {//是否验证接口类中的所有方法 eagerlyValidateMethods(service);//(1) } //动态代理 return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() { privatefinal Platform platform = Platform.get();
@Overridepublic Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { // If the method is a method from Object then defer to normal invocation.//getDeclaringClass()获取方法所在的类 if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args);//调用方法 } if (platform.isDefaultMethod(method)) { return platform.invokeDefaultMethod(method, service, proxy, args); } //获得缓存中的ServiceMethod对象 ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method); //根据参数新建OkHttpCall对象 OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args); // return serviceMethod.callAdapter.adapt(okHttpCall); } }); }