转自:http://tapestry.apache.org/enum-parameter-recipe.html
It's not uncommon to create a component that has a bit of complex behavior that you want to be able to easily control, and an enumerated type (a Java enum) seems like the right approach.
Our example comes from Tapestry's Select component, which has a blankOption parameter that an enum type.
Let's start with the enum type itself:
public enum BlankOption { /** * Always include the blank option, even if the underlying property is required. */ ALWAYS, /** * Never include the blank option, even if the underlying property is optional. */ NEVER, /** * The default: include the blank option if the underlying property is optional. */ AUTO; }
Next, we define the parameter:
The final piece of the puzzle is to inform Tapestry how to convert from a string, such as "never", to a BlankOption value.
public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration) { . . . add(configuration, BlankOption.class); . . . } private static <T extends Enum> void add(Configuration<CoercionTuple> configuration, Class<T> enumType) { configuration.add(CoercionTuple.create(String.class, enumType, StringToEnumCoercion.create(enumType))); }
The TypeCoercer service is ultimately responsible for converting the string to a BlankOption, but we have to tell it how, by contributing an appropriate CoercionTuple. The CoercionTuple identifies the source and target types (String and BlankOption), and an object to perform the coercion (an instance of StringToEnumCoercion, via the create() static method).