chromium/mojo/public/tools/bindings/generators/java_templates/enum_definition.tmpl

{%- macro enum_def(enum, top_level) -%}
public {{ 'static ' if not top_level }}final class {{enum|name}} {
    private static final boolean IS_EXTENSIBLE = {% if enum.extensible %}true{% else %}false{% endif %};
    @IntDef({
{% for field in enum.fields %}
        {{enum|name}}.{{field|name}}
{%-   if not loop.last %},
{%-   endif %}
{%- endfor %}})
    public @interface EnumType {}
{% for field in enum.fields %}
    public static final int {{field|name}} = {{field.numeric_value}};
{%- endfor %}
{%- if enum.min_value is not none %}
    public static final int MIN_VALUE = {{enum.min_value}};
{%- endif %}
{%- if enum.max_value is not none %}
    public static final int MAX_VALUE = {{enum.max_value}};
{%- endif %}
{%- if enum.default_field %}
    public static final int DEFAULT_VALUE = {{enum.default_field.numeric_value}};
{%- endif %}

{%- if enum|covers_continuous_range %}

    public static boolean isKnownValue(int value) {
        return value >= {{enum.min_value}} && value <= {{enum.max_value}};
    }
{%- else %}

    public static boolean isKnownValue(int value) {
{%-   if enum.fields %}
        switch (value) {
{%-     for enum_field in enum.fields|groupby('numeric_value') %}
            case {{enum_field[0]}}:
{%-     endfor %}
                return true;
        }
{%-   endif %}
        return false;
    }
{%- endif %}

    public static void validate(int value) {
        if (IS_EXTENSIBLE || isKnownValue(value)) return;
        throw new org.chromium.mojo.bindings.DeserializationException("Invalid enum value.");
    }

    public static int toKnownValue(int value) {
{%- if enum.extensible and enum.default_field %}
      if (isKnownValue(value)) {
        return value;
      }
      return DEFAULT_VALUE;
{%- else %}
      return value;
{%- endif %}
    }

    private {{enum|name}}() {}
}
{%- endmacro -%}