android中动态代理的demo

来源:互联网 发布:基本面分析软件 编辑:程序博客网 时间:2024/06/04 18:54
  • 首先android中很多都用到了,代理模式,像比较火的网络框架,Retrofit2,(代理+注解+OkHttp)
  • 其实代理模式就是,使用反射完成的,
    写个小小的动态代理,
  • 第一步首先需要一个bean的类。提供一些基本的方法
public class Student implements StudentInfo{    public void play(){        System.out.println("我学习,");    }    public void love(){        System.out.println("我谈恋爱");    }    public void smoke(){        System.out.println("我抽烟");    }}
  • 在写一个此类的接口,接口就是StudentInfo
    代码如下
public interface StudentInfo {    public void play();    public void love();    public void smoke();}
  • 再有就是写一个代理类,将代理跟bean联系起来
public class StudentHanlder implements InvocationHandler  {    public Object invoke(Object arg0, Method arg1, Object[] arg2)            throws Throwable {        StudentHanlder hand = null;        if(arg1.getName().endsWith("smoke")){            System.out.println("学生不能抽烟");        }else{         hand=(StudentHanlder) arg1.invoke(new Student(), null);        }        return hand;    }}
  • 最后就剩下引用了,其实写了那么多,都是在围绕着这个方法写的
public class TestP {    public static void main(String[] args) {        StudentInfo st=(StudentInfo) Proxy.newProxyInstance(Student.class.getClassLoader(),                    new Class[]{StudentInfo.class}, new StudentHanlder());        st.smoke();        st.play();        st.love();    }}

–到此,一个简单的动态代理已经完成

0 0