Annotation Type Builder.Switch


  • @Documented
    @Target({PARAMETER,METHOD})
    public static @interface Builder.Switch
    Applicable only to enum parameters, this annotation turns parameters into switcher methods on builder. Each switcher method applies corresponding constant value. Switch methods are named after parameter name prefixed with properly cased (case transformed) enum constant name.
     class BulbFactory {
       enum Switcher {
         OFF, ON
       }
       @Builder.Factory
       static Bulb bulb(@Builder.Switch Switcher light) {
          return ...
       }
     }
     ... // notice the switcher methods instead of enum initializer
     Bulb b = new BulbBuilder()
        .onLight() // set to Switcher.ON
        .offLight() // set to Switcher.OFF
        .build();
     

    If proper defaultName() value is specified, then one of the state will be considered the default. If no default is specified then it is mandatory to call switcher method once. If default is specified then it switcher method call could be omitted.

     class BulbFactory {
       enum Switcher {
         OFF, ON
       }
       @Builder.Factory
       static Bulb bulb(@Builder.Switch(defaultName = "OFF") Switcher light) {
          return ...
       }
     }
     ... // notice no 'offLight' generated
     Bulb b = new BulbBuilder() // default is Switcher.OFF
        .onLight() // but we can switch to Switcher.ON
        .build();
     

    Also note that with some limitation this annotation works on value type attribute to generate switch option.

    • Optional Element Summary

      Optional Elements 
      Modifier and Type Optional Element Description
      java.lang.String defaultName
      Specify constant name of default enum value for this switch.
    • Element Detail

      • defaultName

        java.lang.String defaultName
        Specify constant name of default enum value for this switch. The name should match constant identifier name. If empty of none specified, then switch will be mandatory to set on builder.
        Returns:
        name enum constant
        Default:
        ""