原文: 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); // 当前页面显示记录
|