ok, I just found it: there is already a converter for enums, I missed
somehow: com.opensymphony.xwork2.util.EnumTypeConverter
Piotr

2008/9/18 Piotr Matkowski <[EMAIL PROTECTED]>

> Hi,
> I was wondering, is there some easy way (annotation, config) to perform
> type conversion on Enum types?
> I noticed that struts does not handle Enum types by default, which is not
> what I expected.
>
> Lets say we have an Enum like that:
>
>     public enum Fruit { ORANGE, APPLE; }
>
> and Action with field and setter:
>
>     private Fruit fruit;
>     public void setFruit(Fruit fruit) { this.fruit = fruit; }
>
> I want to submit String ORANGE from html form and get Fruit.ORANGE object
> in my Action after population.
> I wrote my own type converter, here's the code:
>
> public class EnumConverter extends StrutsTypeConverter {
>     public Object convertFromString(Map context, String[] values, Class
> toClass) {
>         try {
>             return toClass.getMethod("valueOf",
> String.class).invoke(toClass, values[0]);
>         } catch (Exception e) {
>             throw new TypeConversionException(e);
>         }
>     }
>     public String convertToString(Map context, Object o) {
>         return ((Enum) o).name();
>     }
> }
>
> It works for me, but the thing is, the code is quite ugly (i mean the java
> reflection part).
> Does someone know a better way to do that?
> Maybe Enums should be handled by struts by default? Why they aren't
> handled?
> Any comments appreciated,
> regards
> Piotr
>

Reply via email to