首页 > 代码库 > 迭代任意8种数据类型数组

迭代任意8种数据类型数组

写的是一个jstl标签处理器类,可以迭代任意数组

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ForeachTag extends SimpleTagSupport {
    private String var;
    private Object items;
    private Collection collection;

    public void setItems(Object items) {
        this.items = items;
        if (items.getClass().isArray()) {
            this.collection = new ArrayList();
            int length = Array.getLength(items);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(items, i);
                this.collection.add(value);
            }
        }
    }

    public void setVar(String var) {
        this.var = var;
    }

    public void setCollection(Collection collection) {
        this.collection = collection;
    }

    @Override
    public void doTag() throws JspException, IOException {
        Iterator it = this.collection.iterator();
        while (it.hasNext()) {
            Object value = it.next();
            this.getJspContext().setAttribute(var, value);
            this.getJspBody().invoke(null);
        }
    }

}