[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[转帖]演示对Dao接口的封装,解决常见的FieldFilter/Trans的匿名内部类困扰

上一篇:[转帖]对比SQL Server和MySQL数据库函数
下一篇:[备忘]IE10,fckeditor,对象不支持“selectSingleNode”属性或方法

添加日期:2014/5/20 16:45:29 快速返回   返回列表 阅读4153次
原文:
https://gist.github.com/wendal/24b019d39e7e75bb3b21


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.lang.Lang;
import org.nutz.trans.Molecule;
import org.nutz.trans.Trans;
 
public class ExtDaos {
 
    public static Dao ext(Dao dao, FieldFilter filter) {
        return ext(dao, filter, -1);
    }
    
    public static Dao ext(Dao dao, int transLevel) {
        return ext(dao, null, transLevel);
    }
    
    public static Dao ext(Dao dao, FieldFilter filter, int transLevel) {
        return (Dao) Proxy.newProxyInstance(dao.getClass().getClassLoader(), new Class<?>[]{Dao.class}, new ExtDaoInvocationHandler(dao, filter, transLevel));
    }
}
 
class ExtDaoInvocationHandler implements InvocationHandler {
    
    protected ExtDaoInvocationHandler(Dao dao, FieldFilter filter, int transLevel) {
        this.dao = dao;
        this.filter = filter;
        this.transLevel = transLevel;
    }
 
    protected Dao dao;
    protected FieldFilter filter;
    protected int transLevel = -1;
 
    public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
        if (transLevel < 0 && filter == null) {
            return method.invoke(dao, args);
        }
        Molecule<Object> m = new Molecule<Object>() {
            public void run() {
                try {
                    setObj(method.invoke(dao, args));
                }
                catch (IllegalArgumentException e) {
                    throw Lang.wrapThrow(e);
                }
                catch (IllegalAccessException e) {
                    throw Lang.wrapThrow(e);
                }
                catch (InvocationTargetException e) {
                    throw Lang.wrapThrow(e.getTargetException());
                }
            }
        };
        if (transLevel > -1) {
            Trans.exec(transLevel, m);
        } else {
            filter.run(m);
        }
        return m.getObj();
    }
    
}



使用方法举例:


Dao extDao = ExtDaos.ext(this.dao(),FieldFilter.create(StandardLocal.class, "^id$"));
resultList = extDao.query(StandardLocal.class,Cnd.wrap(cond + " order by addTime DESC"), pager); // 当前页面显示记录

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved