0

Just found the following in the Java EE Documentation for javax.faces.component.UISelectMany:

Obtain the Converter using the following algorithm: If the component has an attached Converter, use it. If not, look for a ValueExpression for value (if any). The ValueExpression must point to something that is:

  • An array of primitives (such as int[]). Look up the registered
    by-class Converter for this primitive type.
  • An array of objects (such as Integer[] or String[]). Look up the
    registered by-class Converter for the underlying element type.
  • A java.util.Collection. Do not convert the values.

For a better understanding, I would like to know why the values won't be converted if the ValueExpression is a Collection.

If I want to attach a converter to UISelectMany, do I need to write a converter for the Collection or for the underlying element type?

Matt Handy
  • 29,855
  • 2
  • 89
  • 112

1 Answers1

1

Because EL don't/can't know about the generic list type, because it got lost during runtime. All it knows is that it's a collection of something. The items will be treated as String by default. You need to write a converter for the generic list type, not for the collection. See also this related answer.

To learn more about the type erasure of Java generics, check the generics tutorial.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi BalusC. Thanks for the quick answer. The related answer from the given link makes it clear and I will try it this way. The link to the generics tutorial seems wrong (it redirects to the related answer)? – Matt Handy Mar 22 '11 at 14:45
  • You're welcome. As to the wrong link, sorry, my Ctrl+C didn't do its job. I fixed it. – BalusC Mar 22 '11 at 14:47
  • Yes it works! Great job, BalusC! But I had to override `getAsObject` and `getAsString` methods. Otherwise there were conversion errors like: Error Rendering View[/benutzer/Create.xhtml] java.lang.ClassCastException: jpa.entities.Benutzergruppe cannot be cast to java.lang.Enum at javax.faces.convert.EnumConverter.getAsString – Matt Handy Mar 22 '11 at 15:19
  • The linked related answer concerns when using **enums** as list items. If you aren't using enums as list items, but just normal **classes**, you have to create a "normal" converter with `getAsObject()` and `getAsString()`, indeed. You don't need to extend `EnumConverter`. See also [this another related answer](http://stackoverflow.com/questions/4734580/jsf-2-selection-combo-box-with-without-conversion-strategy/4735322#4735322). – BalusC Mar 22 '11 at 15:22
  • Aha, I can see clearly now, the rain has gone: I had a Netbean's generated converter in my bean with the annotation `@FacesConverter(forClass = Benutzergruppe.class)`. This worked for UISelectOne but not for UISelectMany. The simple fix was to remove the `forClass` attribute to get it working with lists as well. – Matt Handy Mar 22 '11 at 15:45