内部类怎么传递参数给外部类???

来源:互联网 发布:饥荒联机网络启动失败 编辑:程序博客网 时间:2024/05/07 11:46
参考链接:http://wendal.net/404.html
传入: 

//匿名内部类,只能访问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(); 




0 0