I read below in Spring 3.0 document:
Strongly-typed collection (Java 5+ only)
In Java 5 and later, you can use strongly typed collections (using generic types). That is, it is possible to declare a Collection type such that it can only contain String elements (for example). If you are using Spring to dependency-inject a strongly-typed Collection into a bean, you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances are converted to the appropriate type prior to being added to the Collection.
public class Foo {
private Map<String, Float> accounts;
public void setAccounts(Map<String, Float> accounts) {
this.accounts = accounts;
}
}
<beans>
<bean id="foo" class="x.y.Foo">
<property name="accounts">
<map>
<entry key="one" value="9.99"/>
<entry key="two" value="2.75"/>
<entry key="six" value="3.99"/>
</map>
</property>
</bean>
</beans>
When the accounts property of the foo bean is prepared for injection, the generics information about the element type of the strongly-typed Map is available by reflection. Thus Spring's type conversion infrastructure recognizes the various value elements as being of type Float, and the string values 9.99, 2.75, and 3.99 are converted into an actual Float type.
how can this be possible? As I know generic type information is erased during compilation.
This works because types are erased for objects, but not for fields. Have a look at Where are generic types stored in java class files? for a detailed explanation how it works.
In essence, there is a Field.getGenericType()
method introduced in (surprise) 1.5 that always returns reliable generic type of a field. So Spring is capable of reading accounts
generic types (<String, Float>
) via plain reflection.
Note that the same mechanism is used e.g. in jpa. This is completely valid and working:
@Entity
public class Customer {
@OneToMany
private Set<Order> orders;
}
@Entity
public class Order {
@Id
private Integer id;
}
Without this Java 5 feature the JPA provider would not be able to figure out what is the second side of the orders
one-to-many relationship.