package ie.dcu.segment.options; /** * A segmentation algorithm parameter that can assume one of a set of predefined * values. * * @author Kevin McGuinness */ public class EnumOption> extends AbstractOption { private Class clazz; /** * Create an enum option. * * @param clazz * The class of the enum. * @param name * The option name. * @param description * The option description. * @param def * The default value. */ public EnumOption(Class clazz, String name, String description, T def) { super(OptionType.Enumeration, name, description, def); this.clazz = clazz; } public T[] values() { return clazz.getEnumConstants(); } public Conversion convert(Object value) { if (clazz.isInstance(value)) { return valid(clazz.cast(value)); } else if (value != null) { String str = value.toString().trim(); Conversion conv; try { conv = valid(Enum.valueOf(clazz, str)); } catch (IllegalArgumentException e) { conv = invalid("Invalid value \"%s\" for %s", value, getName()); } if (!conv.isOk()) { // Try convert from an integer try { int x = Integer.parseInt(str); T[] v = values(); if (x > 0 && x < v.length) { return valid(v[x]); } } catch (NumberFormatException e) { // Ignore .. we already have an error message from the string conversion } } } return invalid("%s is null", getName()); } }