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



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

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

我有一个这样的课程。

class person {
String name
}

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

我尝试使用时髦的列表集合,但我无法这样做。

这是我的代码。

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)

在你的类testJsonSlurper中,你必须改变这一行

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

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

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

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

​class person {    
String name
person(name){
this.name = name
}
}

最新更新