【问题标题】:Create a list of objects from a list of String in groovy从groovy中的String列表创建对象列表
【发布时间】:2018-05-03 02:46:04
【问题描述】:

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

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

我有一个如下的课程。

class person {
    String name
}

我想从 List 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)

【问题讨论】:

    标签: list groovy collect


    【解决方案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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2014-10-17
      • 2018-01-02
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多