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

Calling a @Canonical Groovy POGO constructor inside Java code

给定此 Groovy 域 class(用于 MongoDB 中的持久性):

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

因为在创建新的计数器时只需要提供 'name',有没有办法调用@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,您可以指定要使用的字段,并在构造函数上拥有更细粒度的控制器。例如:

@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