匿名内部类和动态代理备忘

来源:互联网 发布:手机编辑pdf软件 编辑:程序博客网 时间:2024/06/03 17:38
  • 匿名内部类
    android中仿照xUtils我把http请求的callback回调函数,使用匿名内部类,其中的实现通过annotation注解的形式,关联到外部类的某个方法中。
field.set(handler, new com.lidroid.xutils.http.callback.RequestCallBack(){         @Override         public void onSuccess(ResponseInfo responseInfo) {             try {                  tempOnSuccess.invoke(handler, responseInfo);             } catch (Exception e) {                 LogUtils.e(e.getMessage(), e);             }                                      }}

其中的tempOnSuccess.invoke(handler, responseInfo);handler只得是某个具体的外部类,tempOnSuccess就是hander类中的某个具体方法,而field是把这个callback回调函数的匿名内部类引用为hander的一个成员变量。匿名内部类的主要用于在多线程中传递不同的对象如android中的handler;另外就是界面按钮监听的Listener实现。

  • 动态代理
    目前我的使用是
RestInterface restInterface = ProxyFactory.intance().getDelegate(new RestActive());

new RestActive()是对应的InvocationHandler 这种用法,其实是隐藏了InvocationHandler 反射调用RestActive,可以在调用RestActive的实现方法前后加一个操作。
更好的一种动态代理的使用是mybatis的注解使用方式:

public Record getRecord(long id) {        SqlSession session = this.sqlSessionFactory.openSession();        try {            RecordInterface recordInterface = session.getMapper(RecordInterface.class);            return recordInterface.select(id);        } finally {            session.close();        }    }

开发人员自己提供RecordInterface接口,并把sql语句写在注解中如:

@Select("SELECT * FROM record WHERE id = #{id}")

动态代理返回的就是传入接口,在内部实现的时候把SqlSession 传入到InvocationHandler 中,在invoke反射时,也能获取到注解中的sql语句,通过SqlSession 调用sql语句。这种做法很不错。

0 0