2

I need to get all children Text Field's of a container, wicket provide a method called visitChildren

then I do something like:

(FormComponent<?>[]) visitChildren(TextField.class).toList().toArray();

this example doesn't work, the exception I get is:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lorg.apache.wicket.markup.html.form.FormComponent;

but if I do something like:

List<Component> list = visitChildren(TextField.class).toList();
FormComponent<?>[] array = new FormComponent[list.size()];
for (int x = 0; x < list.size(); x++) {
    array[x] = (FormComponent<?>) list.get(x);
}

it work, why happen that? as far I can see both methods should work

Barney
  • 2,355
  • 3
  • 22
  • 37
osdamv
  • 3,493
  • 2
  • 21
  • 33
  • The below method is the easy way to do it, and [this answer should](http://stackoverflow.com/a/7281807) give you an idea of why it doesn't work. – A--C Mar 14 '13 at 02:07

2 Answers2

4

The first (broken) example is equivalent to:

List<Component> list = visitChildren(TextField.class).toList();
FormComponent<?>[] array = (FormComponent<?>[]) list.toArray();

According to to Javadoc of toArray(), the return type is Object[] but you are trying to cast it to (FormComponent<?>[]), which is an illegal operation.

The tricky part is that we're not performing a cast from Object to FormComponent<?> here.

Rather, the code attempts to cast an array of Object to an array of FormComponent<?>

In order to fix this, try using the alternative toArray method, which takes an object of the desired return type as an argument:

FormComponent<?>[] array = list.toArray(new FormComponent<?>[0])

(Note that we're passing an empty array of FormComponent<?>)

paulkore
  • 665
  • 5
  • 9
0

Try this code as a solution:

toArray(new FormComponent<?>[0])
Perception
  • 79,279
  • 19
  • 185
  • 195
ZhongYu
  • 19,446
  • 5
  • 33
  • 61