Enumeration with array / list values

if (isProductDeliverable) {
  REQUIRED_FIELDS = Arrays.asList(new String[] { Fields.NAME, Fields.EMAIL, Fields.ADDRESS });
} else {
  REQUIRED_FIELDS = Arrays.asList(new String[] { Fields.NAME, Fields.EMAIL });
}

Instead, I want to have a predefined enumeration with two fields - REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTSandREQUIRED_FIELDS_FOR_DOWNLOADABLE_PRODUCTS

I know the theory of enumerations, but I never used them, so I cannot figure out how to do this.

Or maybe a way to request the required fields by passing this "isProductDeliverable" boolean and get the correct field array?

+4
source share
1 answer

Enumerations can have data and behavior as classes. Something like this should work ...

public enum RequiredFields {
    REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTS( Fields.NAME, Fields.EMAIL, Fields.ADDRESS ),
    REQUIRED_FIELDS_FOR_DOWNLOADABLE_PRODUCTS( Fields.NAME, Fields.EMAIL );

    private List<String> fields;
    private RequiredFields(String... fields){
        this.fields = Arrays.asList(fields);
    }
    public List<String> getFields(){
        return fields;
    }
}

Further improvement:

In the above code, the property fieldsis still changed. Someone could do REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTS.getFields().add(..)that would exceed the purpose of the appointment enumin the first place.

:

private RequiredFields(String... fields){
    this.fields = ImmutableList.copyOf(fields); //com.google.common.collect.ImmutableList
}
+6

All Articles