从groovy中的String列表中创建对象列表

时间:2018-05-03 02:46:05

标签: list groovy collect

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

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

我有一个如下课程。

class person {
    String name
}

我想从List l。

创建一个person对象列表

我尝试过使用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)

1 个答案:

答案 0 :(得分:1)

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

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

进入

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

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

如果您不想进行此更改,则需要在类 person 中自行添加构造函数。 添加构造函数后,类 person 应该如下所示。

​class person {    
    String name

    person(name){
        this.name = name
    }
}
相关问题