1 {%- macro enum_value(enum, field, index) -%} 2 {%- if field.value -%} 3 (int) ({{field.value|expression_to_text('i32')}}) 4 {%- elif index == 0 -%} 5 0 6 {%- else -%} 7 {{enum.fields[index - 1]|name}} + 1 8 {%- endif -%} 9 {%- endmacro -%} 10 11 {%- macro enum_def(enum, top_level) -%} 12 public {{ 'static ' if not top_level }}final class {{enum|name}} { 13 14 {% for field in enum.fields %} 15 public static final int {{field|name}} = {{enum_value(enum, field, loop.index0)}}; 16 {% endfor %} 17 18 private static final boolean IS_EXTENSIBLE = {% if enum.extensible %}true{% else %}false{% endif %}; 19 20 public static boolean isKnownValue(int value) { 21 {%- if enum.fields %} 22 switch (value) { 23 {%- for enum_field in enum.fields|groupby('numeric_value') %} 24 case {{enum_field[0]}}: 25 {%- endfor %} 26 return true; 27 } 28 {%- endif %} 29 return false; 30 } 31 32 public static void validate(int value) { 33 if (IS_EXTENSIBLE || isKnownValue(value)) 34 return; 35 36 throw new DeserializationException("Invalid enum value."); 37 } 38 39 private {{enum|name}}() {} 40 41 } 42 {%- endmacro -%} 43