显然他们从apache-commons-collection4
的版本中删除了BeanToPropertyValueTransformer
。
我设法通过defininig定制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"));