首页 > 解决方案 > 从字符串数组填充对象的属性

问题描述

如果我们在 groovy 中有一个对象,例如 Customer[name, email, phone] 和表单中的 String

String infoLine = "Stanislav,stanislav@stackoverflow.com,004612345678" 

解析该字符串并填充该对象的字段的最简单方法是什么?

(我们可以拆分的示例字符串,这就是为什么问题来自字符串数组)

标签: arraysstringgroovy

解决方案


假设你有一个构造函数

Customer(String name, String email, String phone)

你可以做:

new Customer(*infoLine.split(','))

如果您不想编写构造函数,可以让 Groovy 为您创建一个:

import groovy.transform.*

@TupleConstructor
class Customer {
    String name
    String email
    String phone
}

String infoLine = "Stanislav,stanislav@stackoverflow.com,004612345678" 

new Customer(*infoLine.split(','))

甚至更好,@Immutable因为这使得属性final

@Immutable
class Customer {
    String name
    String email
    String phone
}

另一种选择(假设您的字段是按照它们在字符串中出现的顺序定义的,并且没有其他字段),将生成 的映射[name: 'aaa', emai... etc,并告诉 groovy 将映射转换为 Customer,例如:

class Customer {
    String name
    String email
    String phone
}

String infoLine = "Stanislav,stanislav@stackoverflow.com,004612345678" 

def customer = [
    Customer.declaredFields.findAll { !it.synthetic }*.name,
    infoLine.split(',')
].transpose().collectEntries() as Customer

但这感觉有点脆弱,添加注释或构造函数可能更快。


推荐阅读