您的位置:首页 > 编程语言 > Java开发

nutz - Molecule类使用方法(Java匿名内部类的传值)

2015-10-13 16:24 441 查看
博主使用nutz动态表名,查询分表中数据。参考nutzDoc动态表名一节 http://www.nutzam.com/core/dao/dynamic_table_name.html

使用TableName.set的方式可以很容易解决。

List<EventCacheInfo> list = new ArrayList<EventCacheInfo>();
try {
TableName.set("5minutely");
list = dao.query(EventCacheInfo.class, cnd);
} finally {
TableName.clear();
}
return list;
但是用内部类的方式,总也获取不到返回值。错误代码如下:

final Condition cnd1 = cnd;
final List<EventCacheInfo> list = new ArrayList<EventCacheInfo>();
TableName.run("5minutely", new Runnable(){</span>
public void run(){
list = dao.query(EventCacheInfo.class, cnd1); //错误行
}
});
return list;
错误信息:The final local variable list cannot be assigned, since it is defined in an enclosing type

本人基础不好,不明白list为什么不能被赋值,后面再研究。

最终方式,使用Molecule类:

final Condition cnd1 = cnd;
Molecule<List<EventCacheInfo>> mole = new Molecule<List<EventCacheInfo>>(){
public void run(){
setObj(dao.query(EventCacheInfo.class, cnd1));
}
};
TableName.run("5minutely", mole);
return mole.getObj(); //返回list


参考地址:/article/7513521.html

在Nutz中,存在大量需要使用匿名内部类的情况,很多童鞋都对传值很困惑,所以我这里说明一下

传入:

//匿名内部类,只能访问final的本地变量及方法参数

public void addUser(final String name, String passwd, final String userType) {

User user = null;

if ("admin".equal(userType))

user = new AdminUser(name, passwd); //仅作演示.

else

user = new User(name, passwd);

final User _user = user; //因为user变量不能设置为final,所以需要新加一个变量来中转

Trans.run(new Atom(){

public void run() {

dao.insert(_user);

if (log.isDebugEnable())

log.debugf("Add user id=%d, name=%s , type=%s", _user.getId(), name, userType);

}

});

}

传出(获取方法返回值等等):

方法1 – 对象数组法 通过一个final的Object对象数组,存放需要的值

public long countUser(final String userType) {

final Object[] objs = new Object[1];

Trans.run(new Atom(){

public void run() {

objs[0] = dao.count(User.class, Cnd.where('userType', '=', userType));

}

});

return ((Number)objs[0]).longValue();

}

方法2 – ThreadLocal法 通过一个ThreadLocal来存放结果,这个ThreadLocal可以是静态的,供全app使用的

private static final ThreadLocal re = new ThreadLocal(); //自行补上泛型Object

public long countUser(final String userType) {

Trans.run(new Atom(){

public void run() {

re.set(dao.count(User.class, Cnd.where('userType', '=', userType)));

}

});

return ((Number)re.get()).longValue(); //严谨一点的话,应该将ThreadLocal置空

}

方法3 – Molecule法 Molecule类是Nutz内置的抽象类类,实现Runnable和Atom接口,添加了两个获取/设置值的方法.

public long countUser(final String userType) {

Molecule mole = new Molecule() { //需要自行补齐泛型

public void run() {

setObj(dao.count(User.class, Cnd.where('userType', '=', userType)));

}

};

Trans.run(mole);

return ((Number)mole.getObj()).longValue();

}
http://wendal.net/404.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: