简体   繁体   中英

Calling a @Canonical Groovy POGO constructor inside Java code

Given this Groovy domain class (for persistence in MongoDB):

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

Since only 'name' need be supplied when creating a new Counter, is there a way to call the @Canonical-generated map-based constructors, as the Groovy approach below will not compile in Java:

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

Must I either use the implicit setter:

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

Or create a static factory method in the Counter POGO:

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

Enabling the following:

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

The last approach is the one currently used.

If I understand you correctly you don't really want to use @Cannonical , you are more after @TupleConstructor . With this AST you can specify fields you want to use and have more fine grained controller over the constructor. An example could be:

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

For more see http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/TupleConstructor.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM