Java – Defining spring bean using a class with generic parameters

genericsjavaspring

If I have a class that looks something like this:

public class MyClass<T extends Enum<T>> {
  public void setFoo(T[] foos) {
    ....
  }
}

How would I go about declaring this as a bean in my context xml so that I can set the Foo array assuming I know what T is going to be (in my example, let's say T is an enum with the values ONE and TWO)?

At the moment, having something like this is not enough to tell spring what the type T is:

<bean id="myClass" class="example.MyClass">
  <property name="foo">
    <list>
      <value>ONE</value>
      <value>TWO</value>
    </list>
  </property>
</bean>

Edit: Forgot the list tag.

Best Answer

Spring has no generic support for that case, but the compiler just creates a class cast in this case. So the right solution is:

<bean id="myClass" class="example.MyClass">
  <property name="foo">
    <list value-type="example.MyEnumType">
      <value>ONE</value>
      <value>TWO</value>
    </list>
  </property>
</bean>