public <T> T create(final Class<T> service){ Utils.validateServiceInterface(service); if (validateEagerly) { eagerlyValidateMethods(service); } // 动态代理,使用Proxy的一个静态方法newProxyInstance,需要实现InvocationHandler接口 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. // 如果是method是Object的方法,直接正常调用 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); } }); }