Hello,
I just struggled with Spring and understanding why it can't determine a generic type during injection. Please, have a look at this simple code:
(the beanInit method gets called by Spring, it is defined as the default bean init method).Code:public class GenericInjectTest { private Ship< Integer > ship = new Ship< Integer >(); private void beanInit() { System.out.println( ship.getData() ); System.out.println( ship.getData().getClass() ); } public Ship< Integer > getShip() { return ship; } public void setShip( Ship< Integer > ship ) { this.ship = ship; } }
And this is the Ship class:
Here is the (important part of the) Spring context configuration:Code:public class Ship< T > { private T data; public T getData() { return data; } public void setData( T data ) { this.data = data; } }
Code:<bean class="com.test.spring.GenericInjectTest"> <property name="ship.data" value="123" /> </bean>
Looking at the bean definition, we can see that I want to set the property "ship.data" to "123". Since ship is parameterized with "Integer" in the GenericInjectTest class, I would think that Spring is able to detect the correct runtime type, which is Integer, and would convert the "123" to a real Integer.
But this is not the case. When I run the program, the line
prints "123". But the next lineCode:System.out.println( ship.getData() );
throws the exceptionCode:System.out.println( ship.getData().getClass() );
So Spring has injected a String for the property "ship.data", not an Integer.Code:java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Is it the case, that Spring can't handle those generics, or am I doing anything wrong here?
Thanks a lot for your help


Reply With Quote

