Annotation Interface Key


@Target(FIELD) @Retention(RUNTIME) @Documented public @interface Key

Designates a field as the key of the containing class. The main usage of this is that this field is automatically used when an instance of the class is put into a map.

In a hierarchy of model objects, the ancestor model defines whether the hierarchy is keyed or not.

it is illegal

  • to put this annotation on a field of any other class than the ancestor of a hierarchy
  • to put this annotation on more than one field in a class.

Marking a field as key has the following consequences:

  • a constructor is created with a single argument of the type of the key field, the default constructor is removed
  • the create method and all adder / setter methods creating an instance of this type take an additional argument of the annotated type
  • for this field, no dsl setter methods are created

 given:
 @DSL
 class Foo {
   @Key String name
 }

 when:
 instance = Foo.Create.With("Dieter") {}

 then:
 instance.name == "Dieter"
 

Example with map


  given:
 @DSL
  class Foo {
    Map<String, Bar> bars
  }

 @DSL
  class Bar {
    @Key String name
    String url
  }

  when:
  instance = Foo.Create.With {
    bars {
      bar("Dieter") { url "1" }
      bar("Klaus") { url "2" }
    }
  }

  then:
  instance.bars.Dieter.url == "1"
  instance.bars.Klaus.url == "2"

 

Currently only fields of type String are allowed to be keys.