You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中字符串列表转Person对象列表报错,求解决方法

解决Groovy中collect转换字符串列表为Person对象列表的问题

嘿,我瞅了下你的代码,问题出在person类的构造方法上哦!你定义的person类只有一个name属性,但Groovy默认只会给它生成无参构造函数,而你在collect里直接写new person(it),是在尝试调用一个接受String参数的构造方法,这显然找不到对应的实现,所以才会抛出那个运行时异常。

下面给你几种可行的解决方案,按需选择就行:

方案1:显式添加带参数的构造函数

直接给person类写一个接受name参数的构造方法,这样就能直接通过new person(it)创建对象了:

class person { 
    String name 
    // 添加接受name参数的构造方法
    person(String name) {
        this.name = name
    }
}

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

方案2:利用Groovy的命名参数特性(无需写构造函数)

Groovy支持在创建对象时直接通过命名参数给属性赋值,不用额外写构造方法,代码更简洁:

class person { 
    String name 
}

class testJsonSlurper { 
    static void main(String[] args) { 
        List l = ["1","2","3"] 
        // 通过命名参数给name属性赋值
        def l2 = l.collect { new person(name: it) } 
        println(l2) 
    }
}

方案3:用Groovy注解自动生成构造函数(推荐)

如果你的person类以后可能添加更多属性,或者需要更友好的toString输出,可以用@Canonical注解,它会自动帮你生成带所有属性参数的构造函数、toString、equals和hashCode方法:

import groovy.transform.Canonical

@Canonical
class person { 
    String name 
}

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

用这个注解的话,打印l2的时候会直接显示每个person对象的name值,比如[person(1), person(2), person(3)],而不是默认的内存地址,调试起来更方便。

内容的提问来源于stack exchange,提问作者Apoorva sahay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:33:32