Home > Java > javaTutorial > Java anonymous inner class passing value

Java anonymous inner class passing value

高洛峰
Release: 2016-12-15 13:01:08
Original
1253 people have browsed it

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); 
        } 
    }); 
}
Copy after login

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(); 
}
Copy after login


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置空 
}
Copy after login


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(); 
}
Copy after login



More Java For articles related to value-passing of anonymous inner classes, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template