The following generic method iterates over an enum type and retrieves its values (ordinals, i.e. their underlying integer value) and their names:
The invocation of this method might be:protected void addType(Class clazz, Enum<?>[] enumValues) {
List<SelectItem> selectItems = new ArrayList<SelectItem>();
for(Enum<?> value : enumValues) {
SelectItem item = new SelectItem(value.ordinal(),
value.name(), value.name());
selectItems.add(item);
}
itemLists.put(clazz, selectItems);
}
In this example RoleType is defined as a enum with one or more values.addType(RoleType.class, RoleType.values());
Another option would have been to declare the method as:
However, I decided that the code would look harder to read, so I used the wildcard version instead. Let me know if this example was helpful.protected <T extends Enum<T>> void addType(Class clazz, T[] enumValues) {...}
No comments:
Post a Comment