In Nutz, there are a lot of situations where anonymous internal classes need to be used. Many children are confused about passing values, so I will explain here
Incoming:
//匿名内部类,只能访问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); } }); }
Outgoing (getting method return value, etc.):
Method 1 – The object array method uses a final Object object array to store the required values
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(); }
Method 2 – The ThreadLocal method uses a ThreadLocal to store the results. This ThreadLocal can be static and used by the entire 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置空 }
Method 3 – Molecule method The Molecule class is Nutz’s built-in abstract class, which implements the Runnable and Atom interfaces and adds two methods to get/set values.
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(); }
More Java For articles related to value-passing of anonymous inner classes, please pay attention to the PHP Chinese website!