Groovy @Canonical和@TupleConstructor使用抽象基类窒息

时间:2018-01-05 03:18:52

标签: groovy constructor

我有以下Groovy类:

while (true) {
    ConsumerRecords<String, String> records = consumer.poll(100);
    for  (ConsumerRecord<String, String> record : records) {
        DoSomeProcessing (record.value());
    }
    consumer.commitAsync();
}

private void DoSomeProcessing(String record) {
    //make an external call to a system which can take random time for different requests or timeout in 5 seconds.
}

然后在运行时我创建@Canonical abstract class BaseEntity { Long id String refId } @Canonical @TupleConstructor(includeSuperFields = true, includeFields = true) @ToString(includeSuperProperties = true) class GroceryItem extends BaseEntity { String name Integer quantity } 的实例:

GroceryItem

当这个构造函数运行时,我得到以下异常:

GroceryItem cheeseWedges = new GroceryItem(1L,
    '067e6162-3b6f-4ae2-a171-2470b63dff00', 'Cheese Wedges', 4)

这里发生了什么?解决了什么? groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.example.myapp.GroceryItem(java.lang.Long, java.lang.String, java.lang.String, java.lang.Integer) at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1732) at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1532) at org.codehaus.groovy.runtime.callsite.MetaClassConstructorSite.callConstructor(MetaClassConstructorSite.java:49) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60) 是抽象的,这会导致问题吗?我似乎记得几年前这些注释+ ABC的问题类似。

1 个答案:

答案 0 :(得分:1)

希望您可能知道Canonical本身是ToStringTupleConstructorEqualsAndHashCode的组合。

  • 由于您明确指定TupleConsturctor选项,因此可能会删除子类CanonicalGroceryItem
  • 除此之外,需要includeSuperProperties=true的{​​{1}}选项才能实现所需的行为。以下是blog,您可以参考更多详情。
  • 由于基类为TupleConsturctor,因此不需要注释。
  • 如果基类是常规类,并且您想要调用基类构造函数的abstract,那么super()选项可以包含在子类的callSuper=true注释中。当然,基类的时间也需要TupleConstructor
  • 如果使用基类中的访问修饰符定义属性,请说Canonical,则需要将public String description选项添加到子类的includeSuperFields=true

这是固定的代码段:

TupleConstructor

您可以在线快速尝试 demo