Grails data binding - command objects with Lists

天大地大妈咪最大 提交于 2019-11-28 22:10:51

Grails requires an command with existing list, that will be filled with data from reques.

If you know exact number of units, say 3, you can:

class Tracker {
    String name
    String description
    List<Unit> units = [new Unit(), new Unit(), new Unit()]
}

or use LazyList from apache commons collections

import org.apache.commons.collections.ListUtils
import org.apache.commons.collections.Factory
class Tracker {
    String name
    String description
    List<Unit> units = ListUtils.lazyList([], {new Unit()} as Factory)
}
micha

Since Groovy 1.8.7 the List interface has a method called withLazyDefault that can be used instead of apache commons ListUtils:

List<Unit> units = [].withLazyDefault { new Unit() }

This creates a new Unit instance every time units is accessed with a non-existent index.

See the documentation of withLazyDefault for more details. I also wrote a small blog post about this a few days ago.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!