I have an Enum like this
package com.example;
public enum CoverageEnum {
COUNTRY,
REGIONAL,
COUNTY
}
I would like to iterate
If you're using Spring MVC, you can accomplish your goal with the following syntactic blessing:
<form:form method="post" modelAttribute="cluster" cssClass="form" enctype="multipart/form-data">
<form:label path="clusterType">Cluster Type
<form:errors path="clusterType" cssClass="error" />
</form:label>
<form:select items="${clusterTypes}" var="type" path="clusterType"/>
</form:form>
where your model attribute (ie, bean/data entity to populate) is named cluster and you have already populated the model with an enum array of values named clusterTypes. The <form:error>
part is very much optional.
In Spring MVC land, you can also auto-populate clusterTypes
into your model like this
@ModelAttribute("clusterTypes")
public MyClusterType[] populateClusterTypes() {
return MyClusterType.values();
}
If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:
<c:forEach var="type" items="${myprefix:getValues()}">
EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:
public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
try {
Method m = klass.getMethod("values", null);
Object obj = m.invoke(null, null);
return (Enum<T>[])obj;
} catch(Exception ex) {
//shouldn't happen...
return null;
}
}