显然他们BeanToPropertyValueTransformer
从apache-commons-collection4
.
我设法通过定义自定义来实现相同的行为Transformer
。泛型的引入消除了强制转换输出集合的必要性:
Collection<MyInputType> myCollection = ...
Collection<MyType> myTypes = CollectionUtils.collect(myCollection, new Transformer<MyInputType, MyType>() {
@Override
public MyType transform(MyInputType input) {
return input.getMyProperty();
}
}
您也可以编写自己的Transformer
使用反射的
class ReflectionTransformer<O>
implements
Transformer<Object, O> {
private String reflectionString;
public ReflectionTransformer(String reflectionString) {
this.reflectionString = reflectionString;
}
@SuppressWarnings("unchecked")
@Override
public O transform(
Object input) {
try {
return (O) BeanUtils.getProperty(input, reflectionString);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
并像以前一样使用它BeanToPropertyValueTransformer
Collection<MyType> myTypes = CollectionUtils.collect(myCollection, new ReflectionTransformer<MyType>("myProperty"));