Java匿名內部類的傳值

在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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章