7.4.2 Strongly-typed collection

With the introduction of generic types in Java 5, you can use strongly typed collections. That is, it is possible to declare a Collection type such that it can only containString 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.

通过Java 5的泛型介绍,你可以使用强类型集合.这也就是说,你可以声明一个它只能包含String元素(比如)的集合类型.如果你使用Spring去依赖注入了一个强类型集合到一个bean中,你可以使用Spring的类型转换支持的优势,将你的强类型集合实例元素转换成合适的类型在它被添加到集合中之前.

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<String, Float> 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.

 foo bean的 accounts 属性被准备注入的时候,已经可以通过反射获取强类型 Map<String, Float> 的元素类型的泛型信息了.Spring的类型转换器能够识别出多个值的类型是Float,然后String类型的值9.99, 2.75和3.99被转换到真正的Float类型中去.

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80758304