UISelectMany on the <T> list raises java.lang.ClassCastException: java.lang.String cannot be attributed to T

I use <p:selectCheckboxMenu>on List<Long>:

<p:selectCheckboxMenu value="#{bean.selectedItems}">
    <f:selectItems value="#{bean.availableItems}" />
</p:selectCheckboxMenu>
private List<Long> selectedItems;
private Map<String, Long> availableItems;

When submitting a form and navigating through selected items as shown below,

for (int i = 0; i < selectedItems.size(); i++) {
    Long id = selectedItems.get(i);
    // ...
}

Then I get a cast class exception:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
    at com.example.Bean.submit(Bean.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 27 more

The same thing happens with <p:selectManyCheckbox>, <p:selectManyMenu>, <h:selectManyMenu>etc. All components with multiple choices basically. It works fine in <p:selectOneMenu>all other components of the same choice with a single value Long.

How is this caused and how can I solve it?

+4
source share
1 answer

Your problem is caused by the following facts:

  • Java .
  • EL- , .
  • HTTP- String s.

: EL . EL a List<Long>, a List. , , EL String List . Long , , , ClassCastException.

: String - Long. JSF LongConverter , javax.faces.Long. .

<p:selectCheckboxMenu ... converter="javax.faces.Long">

, , List<T> T[]. , EL Long , , . , , , .

private Long[] selectedItems;

(javabean, entity, POJO ..) select Long, JSF , . Converter Converter forClass, T[]. 'null Converter'.

+8

All Articles