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对象又通过不同的抽象工厂适配器生成不同的返回值对象。