Defining spring bean using a class with generic parameters

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.

3 thoughts on “Defining spring bean using a class with generic parameters

  1. user

    Consider working example.

    <bean id="simpleInt" 
          class="org.nipr.gateway.service.transaction_assistant.GenericSimple">
        <constructor-arg>
            <!-- this can be any full path to a class -->
            <value>java.lang.Integer</value> 
        </constructor-arg>
    </bean>
    

    and

    <bean id="simpleString"  
          class="org.nipr.gateway.service.transaction_assistant.GenericSimple">
        <constructor-arg>
            <value>java.lang.String</value>
        </constructor-arg>
    </bean>
    

    Simple generic class:

    public class GenericSimple<T> {
        private Class<T> type;
        public GenericSimple(Class<T> type) {
            this.type = type;
        }
        public T get( T t) {
            return t;
        }
    }
    

    And finally, the test method (using factory):

    public void testGeneric(){
        Factory factory = new Factory(new String[]{"config/beanForGenericTest.xml"});
    
        GenericSimple<Integer> simpleInt 
            = (GenericSimple<Integer>)factory.getClass("simpleInt");
        System.out.println(simpleInt.get(Integer.valueOf(100)));
        Assert.assertTrue(simpleInt.get(Integer.valueOf(100)).equals(100));
    
        GenericSimple<String> simpleString = 
            (GenericSimple<String>)factory.getClass("simpleString");
        System.out.println(simpleString.get(new String("Rockets go fast.")));
        Assert.assertTrue(simpleString.get("Rockets go fast.")
            .equals("Rockets go fast."));
    }
    
    Reply
  2. user

    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>
    
    Reply

Leave a Reply

Your email address will not be published.