Add support for conversion between String and Enum to Classes.coerce

XMLWordPrintable

    • Type: New Feature
    • Resolution: Unresolved
    • Priority: Normal
    • None
    • Affects Version/s: 7.0.3
    • Component/s: Databind 2
    • None
    • None

      Use case: a parameter is passed in query string, e.g. /app/test.zul?type=enumValue

      Then I want to access that parameter value in my ViewModel like this:

      public enum TypeEnum {
          enumValue,
          enumValue2;
      }
      
      // ViewModel method
      @Init
      public void init(@QueryParam("type") TypeEnum type) {
       // ...
      }
      

      Currently it fails with Exception:

      ...
      Caused by: java.lang.ClassCastException: class java.lang.String cannot be converted to class foo.model.TypeEnum.
      	at org.zkoss.lang.Classes.coerce(Classes.java:1443)
      	at org.zkoss.bind.impl.ParamCall$5.resolveParameter(ParamCall.java:262)
      	at org.zkoss.bind.impl.ParamCall$5.resolveParameter(ParamCall.java:258)
      	at org.zkoss.bind.impl.ParamCall.resolveParameter(ParamCall.java:149)
      	at org.zkoss.bind.impl.ParamCall.call(ParamCall.java:118)
      	at org.zkoss.bind.impl.AbstractAnnotatedMethodInvoker.invokeMethod(AbstractAnnotatedMethodInvoker.java:90)
      	... 177 more
      Caused by: java.lang.NoSuchMethodException: foo.model.TypeEnum: no constructor for [enumValue]
      	at org.zkoss.lang.Classes.newInstance(Classes.java:99)
      	at org.zkoss.lang.Classes.coerce(Classes.java:1441)
      	... 182 more
      

      It would be nice if Classes.coerce would convert between String and Enum automatically by calling Enum#name() / Enum#valueOf().
      Note: Conversion by means of Enum#valueOf could handle IllegalArgumentException by returning null (not sure which way is better)

            Assignee:
            Unassigned
            Reporter:
            gediminas
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated: