3

I have a property in my JSF managed bean:

private List<Long> selectedDataSets;

I initialize the list like this within an other method:

ArrayList<Long> longList = new ArrayList<>();

What happens is I get java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long right when it jumps on this foreach:

for (Long CRC : selectedDataSets) { ... }

Which is very odd. Debug shows that selectedDataSets are full of String values, but I thought that's not even possible. Please describe me what exactly happened here.

Daniel Szalay
  • 4,041
  • 12
  • 57
  • 103
  • 1
    That would depend totally on how and where you filled `longList`... could you have subverted the type checking in a method somewhere? You've omitted the most important code from your sample. – Jim Garrison Nov 02 '11 at 19:45
  • 1
    Please provide an [SSCCE](http://sscce.org). – aioobe Nov 02 '11 at 19:45

1 Answers1

4

Apparently you bound the property to an UISelectMany component like <h:selectManyCheckbox> or <selectManyListbox> without explicitly specifying a Converter. In Java, the generic type is erased during runtime and JSF (more specifically, EL) does not know anything about the generic list type at all and defaults to String unless told otherwise by a Converter. It's String because that's just the default value type of HttpServletRequest#getParameterMap(). EL fills the list with submitted values by reflection and does not take any generic types into account.

So, for example this should do it for you, with help of the builtin LongConverter:

<h:selectManyCheckbox value="#{bean.selectedDataSets}" converter="javax.faces.Long">

See also:


Note that this has nothing to do with Java 7's diamond operator. You would have exactly the same problem when you have experimented with new ArrayList<Long>().

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • *embarrassed*. I think I never used any type other than `String`, so it would have been natural for me if it would have worked automatically with generics. – Daniel Szalay Nov 02 '11 at 20:06
  • 1
    Please note that JSF/EL has also builtin coercions for standard Java types like `int`, `Integer`, `long`, `Long`, `boolean`, `Boolean`, `enum`, `Enum`, etc. This way you'd never need to explicitly specify a `Converter` for them. But for a `List` of them it's indeed a different story. – BalusC Nov 02 '11 at 20:08