gpt4 book ai didi

java - 在 Java 代码中调用 @Canonical Groovy POGO 构造函数

转载 作者:行者123 更新时间:2023-12-01 11:29:22 28 4
gpt4 key购买 nike

给定这个 Groovy 域类(用于在 MongoDB 中持久化):

@Canonical
class Counter {
@Id String id
String name
long count = 0
Date createdTimestamp = new Date()
Date updatedTimestamp = new Date()
}

由于创建新计数器时只需要提供“名称”,因此有没有办法调用 @Canonical 生成的基于映射的构造函数,因为下面的 Groovy 方法不会在 Java 中编译:

// Invalid Java code
counterRepository.save(new Counter(name: newCounterName));

我必须使用隐式 setter 吗:

// Valid, but a bit verbose, Java code
Counter counter = new Counter();
counter.setName(newCounterName);
counterRepository.save(counter);

或者在 Counter POGO 中创建一个静态工厂方法:

static Counter init(String newCounterName) {
return new Counter(name: newCounterName)
}

启用以下功能:

// Valid, concise, but perhaps/hopefully redundant?
counterRepository.save(Counter.init(counterName));

最后一种方法是当前使用的方法。

最佳答案

如果我理解正确的话,你并不是真的想使用@Cannonical,你更喜欢@TupleConstructor。使用此 AST,您可以指定要使用的字段,并在构造函数上拥有更细粒度的 Controller 。一个例子可以是:

@TupleConstructor(includes=['name'])
class Counter {
@Id String id
String name
long count = 0
Date createdTimestamp = new Date()
Date updatedTimestamp = new Date()
}

更多信息请参见http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/TupleConstructor.html

关于java - 在 Java 代码中调用 @Canonical Groovy POGO 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544905/

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