Java BeanProperty值转换器和commons-Collections 4
在Java BeanProperty值转换器和commons-Collections 4,java,apache-commons-beanutils,apache-commons-collection,Java,Apache Commons Beanutils,Apache Commons Collection,在commons collections 3.2.1中,以下一行代码很好地检索了myCollection中对象的myProperty值: Collection<MyType> myTypes = (Collection<MyType>) CollectionUtils.collect(myCollection, new BeanToPropertyValueTransformer("myProperty")) Collection myTypes=(Collection
commons collections 3.2.1
中,以下一行代码很好地检索了myCollection
中对象的myProperty
值:
Collection<MyType> myTypes = (Collection<MyType>) CollectionUtils.collect(myCollection, new BeanToPropertyValueTransformer("myProperty"))
Collection myTypes=(Collection)CollectionUtils.collect(myCollection,新的BeantPropertyValueTransformer(“myProperty”))
唯一的缺点是不支持泛型,所以需要进行类型转换
什么样的解决方案能够在
commons-collection4
中工作,利用泛型?显然,他们从apache-commons-collection4
的发行版中删除了BeantPropertyValueTransformer
我通过定义一个自定义的转换器
实现了相同的行为。泛型的引入消除了强制转换输出集合的必要性:
Collection<MyInputType> myCollection = ...
Collection<MyType> myTypes = CollectionUtils.collect(myCollection, new Transformer<MyInputType, MyType>() {
@Override
public MyType transform(MyInputType input) {
return input.getMyProperty();
}
}
并使用与使用BeanPropertyValueTransformer
Collection<MyType> myTypes = CollectionUtils.collect(myCollection, new ReflectionTransformer<MyType>("myProperty"));
Collection myTypes=CollectionUtils.collect(myCollection,新的ReflectionTransformer(“myProperty”);
Collection<MyType> myTypes = CollectionUtils.collect(myCollection, new ReflectionTransformer<MyType>("myProperty"));