LazyList
Struts で一覧入力を可能にするために Jakarta Commons の LazyList を使用したサンプル。
import org.apache.commons.collections.list.LazyList; public class ListSampleForm extends ActionForm { private List dataList = LazyList.decorate(new LinkedList(), new Factory() { public Object create() { return new SubBean(); } }); public List getDataList() { return dataList; } public void setDataList(List dataList) { this.dataList = dataList; } }
<%-- logic:iterate で出力する場合 --%> <logic:iterate id="dataList" name="listForm" property="dataList" indexId="index"> <html:text name="dataList" property="bbb" indexed="true"/> </logic:iterate> <%-- nested:iterate で出力する場合 --%> <nested:iterate property="dataList"> <nested:text property="bbb"/> </nested:iterate>
Jakarta Commons の LazyList をもっとエレガントに実装。ジェネリクスを使用すれば更に良い。
public class LazyList extends LinkedList { private Class clazz; public LazyList(Class clazz) { this.clazz = clazz; } public Object get(int i) { try { while (size() <= i) { add(clazz.newInstance()); } } cache (Exception e) { throw new IllegalStateException(e); } return super.get(i); } }
public class ListSampleForm extends ActionForm { private List dataList = new LazyList(SubBean.class); public List getDataList() { return dataList; } public void setDataList(List dataList) { this.dataList = dataList; } }
おまけ。int 引数 getter を使用した例。
public class HogeForm { private List data; public List getData(int i){ while (this.data.size() <= i) { this.data.add(new HogeDatum()); } return this.data.get(i); } }
<logic:iterate id="data" name="hoge" property="data" type="HogeDatum"> <html:text name="data" property="name" indexed="true"/> </logic:iterate>