Groovy 元组构造函数创建

  • 2019 年 10 月 4 日
  • 筆記

Groovy 1.8添加了@TupleConstructor注释。 通过这个注释,我们可以在编译时自动创建一个元组构造函数。 因此构造函数可以在编译的类中找到。 对于类中的每个属性,将使用默认值创建构造函数中的参数。 类中定义的属性的顺序还定义了构造函数中参数的顺序。 因为参数具有默认值,所以我们可以使用Groovy语法,并在使用构造函数时将参数留在参数列表的末尾。

我们还可以包含字段作为构造函数参数。 我们使用注释属性includeFields=true来激活它。

如果我们在类中定义构造函数而不是TupleConstructor注释将不会创建额外的构造函数。 但我们可以使用属性值force=true覆盖此行为。 我们必须确保自己没有构造函数冲突,因为现在注释将创建额外的构造函数。

如果我们的类扩展了另一个类,并且我们想要包含超类的属性或字段,我们可以使用属性includeSuperPropertiesincludeSuperFields。 我们甚至可以指示注释在构造函数中创建代码,以使用属性调用超类的超级构造函数。 我们必须设置注释属性callSuper=true来实现这一点。

import groovy.transform.TupleConstructor    @TupleConstructor()  class Person {      String name      List likes      private boolean active = false  }    def person = new Person('mrhaki', ['Groovy', 'Java'])    assert person.name == 'mrhaki'  assert person.likes == ['Groovy', 'Java']    person = new Person('mrhaki')    assert person.name == 'mrhaki'  assert !person.likes  // includeFields in the constructor creation.  import groovy.transform.TupleConstructor    @TupleConstructor(includeFields=true)  class Person {      String name      List likes      private boolean active = false        boolean isActivated() { active }  }    def person = new Person('mrhaki', ['Groovy', 'Java'], true)    assert person.name == 'mrhaki'  assert person.likes == ['Groovy', 'Java']  assert person.activated  // use force attribute to force creation of constructor  // even if we define our own constructors.  import groovy.transform.TupleConstructor    @TupleConstructor(force=true)  class Person {      String name      List likes      private boolean active = false        Person(boolean active) {          this.active = active      }        boolean isActivated() { active }  }    def person = new Person('mrhaki', ['Groovy', 'Java'])    assert person.name == 'mrhaki'  assert person.likes == ['Groovy', 'Java']  assert !person.activated    person = new Person(true)    assert person.activated  // include properties and fields from super class.  import groovy.transform.TupleConstructor    @TupleConstructor(includeFields=true)  class Person {      String name      List likes      private boolean active = false        boolean isActivated() { active }  }    @TupleConstructor(callSuper=true, includeSuperProperties=true, includeSuperFields=true)  class Student extends Person {      List courses  }    def student = new Student('mrhaki', ['Groovy', 'Java'], true, ['IT'])    assert student.name == 'mrhaki'  assert student.likes == ['Groovy', 'Java']  assert student.activated  assert student.courses == ['IT']