从 groovy 中的字符串列表创建对象列表

Create a list of objects from a list of String in groovy

我有一个字符串列表如下。

List l = ["1","2","3"]

我有一个 class 如下。

class person {
    String name
}

我想从列表 l 创建一个人员对象列表。

我试过使用 groovy list collect 但我做不到。

这是我的代码。

class testJsonSlurper {
    static void main(String[] args) {
        List l = ["1","2","3"]
        def l2 = l.collect { new person(it) }
        println(l2)
    }
}

但是我收到以下错误。

Exception in thread "main" groovy.lang.GroovyRuntimeException: Could not find matching constructor for: testJsonSlurper$person(java.lang.String)

在您的 class testJsonSlurper 中,您必须更改此行

def l2 = l.collect { new person(it) }

进入

def l2 = l.collect { new person(name:it) }

这就是我们所说的命名参数构造函数。您可以找到更多关于 命名参数构造函数 here.

如果你不想做这个改变,那么你需要自己在classperson中添加构造函数。 添加构造函数后 class person 应该如下所示。

​class person {    
    String name

    person(name){
        this.name = name
    }
}