gpt4 book ai didi

java - 是否有通过 "with"-function 进行对象构造的更常规替代方案

转载 作者:行者123 更新时间:2023-12-01 07:07:00 26 4
gpt4 key购买 nike

我们仅将 Groovy 用于测试,这意味着我们所有的域类等仍然是普通的 Java 类。为了轻松创建测试数据,我们目前使用以下技术:

Java 类示例


public class Domain {
private String name;
private int id;
private Domain parent;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Domain getParent() {
return parent;
}

public void setParent(Domain parent) {
this.parent = parent;
}
}

Groovy 中的对象构造示例


Domain test = new Domain().with {
name = "Test Object"
id = 42

delegate
}

嵌套构造


Domain test = new Domain().with {
name = "Test Object"
id = 42
parent = new Domain().with {
name = "Parent"
id = 47

delegate
}

delegate
}

正如您所看到的,Domain 对象已创建,然后通过 Groovy 的 with 函数进行配置。这里丑陋的是最后的委托(delegate)再次返回实际对象。如果我们不在这里使用它,结果将是 42 而不是配置的对象。

是否有一种 Groovier 方法可以使用标准 Groovy 函数来执行此操作,因此不需要类别、混合或自定义帮助函数。

<小时/>

编辑:添加了嵌套对象构造示例。

编辑2:两个答案都有效:


import spock.lang.Specification


class StackOverflow extends Specification {

def "Answer Ian Roberts" () {
when:
Domain test = new Domain(
name: "Test object",
id: 42,
parent: new Domain(name: "Parent", id: 47))

then:
test.name == "Test object"
test.id == 42
test.parent.name == "Parent"
test.parent.id == 47
}

def "Answer tim_yates"() {
when:
Domain test = [
name: "Test object",
id: 42,
parent: [name:"Parent", id:47]
]

then:
test.name == "Test object"
test.id == 42
test.parent.name == "Parent"
test.parent.id == 47
}
}

最佳答案

您可以对任何具有无参构造函数的 Java 类使用“命名参数”映射构造函数语法:

Domain test = new Domain(
name:"Test object",
id:42,
parent:new Domain(name:"Parent", id:47))

在幕后,Groovy 将调用无参数构造函数,然后调用 Java Bean 属性 setter ,然后返回结果对象。

关于java - 是否有通过 "with"-function 进行对象构造的更常规替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21860624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com