Android使用动态代理模仿Retrofit的create方法,使其可以返回任意的接口类型
一、概述
本节将模仿一下Retrofit的create泛型方法,根据传入的interface,生成一个代理对象。同个这个小例子可以加深对retrofit的理解
二、实际代码
定义一个book接口,通过动态带来创建其实现类,并调用其实现类的book方法
1.Book.java:普通的接口
2.ApiBookInterface.java:定义一个普通的接口
3.MyRetrofit.java:create方法生成代理对象
4.JavaBook.java 实现了Book.java接口的类
5.测试方法
a.Book.java
package com.yw.rxjava3demo.proxy; /** * 所有书本的基类 * create by yangwei * on 2020-02-26 12:16 */ public interface Book { void read(); }
b.JavaBook.java
package com.yw.rxjava3demo.proxy; import com.yw.rxjava3demo.MyLog; /** * create by yangwei * on 2020-02-26 12:17 */ public class JavaBook implements Book{ @Override public void read() { MyLog.log("《深入Java虚拟机》"); } }
c.ApiBookInterface.java
package com.yw.rxjava3demo.proxy; /** * create by yangwei * on 2020-02-26 12:24 */ public interface ApiBookInterface { Book getBook(); }
d.MyRetrofit.java
package com.yw.rxjava3demo.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * create by yangwei * on 2020-02-26 12:18 */ public class MyRetrofit { private ProxyBookAdapterFactory proxyBookAdapterFactory; public MyRetrofit(ProxyBookAdapterFactory proxyBookAdapterFactory) { this.proxyBookAdapterFactory = proxyBookAdapterFactory; } public <T> T create(final Class<T> bookClass) { return (T) Proxy.newProxyInstance(bookClass.getClassLoader(), new Class<?>[]{bookClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //不走代理方法,直接走原始方法 if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } return new AndroidBook(); } }); } public static final class Builder { private ProxyBookAdapterFactory proxyBookAdapterFactory; public Builder setProxyBookAdapterFactory(ProxyBookAdapterFactory proxyBookAdapterFactory) { this.proxyBookAdapterFactory = proxyBookAdapterFactory; return this; } public MyRetrofit build() { return new MyRetrofit(proxyBookAdapterFactory); } } }
e.测试方法
ApiBookInterface apiBookInterface = new com.yw.rxjava3demo.proxy.MyRetrofit.Builder().build().create(ApiBookInterface.class); com.yw.rxjava3demo.proxy.Book book = apiBookInterface.getBook(); book.read();
f.测试结果,会输出《深入java虚拟机》
2020-02-26 13:29:02.953 1604-1604/? E/MyLog: 《深入Java虚拟机》
总结:希望通过这个小例子大家能够对Proxy有更深的理解,同时也对Retrofit的create方法加深印象。