问题描述
我在Spring 3.0文档中阅读了以下内容:
I read below in Spring 3.0 document:
严格类型的集合(仅Java 5 +)
在Java 5和更高版本中,可以使用强类型的集合(使用泛型类型).也就是说,可以声明一个Collection类型,使其仅包含String元素(例如).如果您使用Spring将强类型的Collection依赖注入到bean中,则可以利用Spring的类型转换支持,以便在将强类型的Collection实例的元素添加到Bean中之前将其转换为适当的类型.集合.
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>
当准备注入foo bean的accounts属性时,可以通过反射获得有关强类型Map的元素类型的泛型信息.因此,Spring的类型转换基础结构可以识别各种值元素(类型为Float)以及字符串值9.99、2.75和3.99都将转换为实际的Float类型.
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.
推荐答案
之所以有效,是因为对象的类型被擦除,但字段不被擦除.看看 java类文件中存储的泛型类型在哪里?以详细说明其工作原理.
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.
从本质上讲,有一个 Field.getGenericType()
方法始终返回可靠的字段通用类型.因此,Spring 能够通过普通反射读取 accounts
通用类型(< String,Float>
).
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.
请注意,使用了相同的机制,例如在 jpa 的问题中.这是完全有效且有效的:
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;
}
如果没有Java 5功能,JPA提供程序将无法弄清 orders
一对多关系的第二面.
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.
这篇关于Spring如何在运行时获取有关“强类型集合"的泛型类型信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!