Nutz匿名内部类的传值

Posted on

Nutz匿名内部类的传值

在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();

}

希望本站内容对您有点用处,有什么疑问或建议请在后面留言评论
转载请注明作者(RobinChia)和出处 It so life ,请勿用于任何商业用途