2

commons-collections 3.2.1下面的一行工作很好地检索对象的myProperty值内myCollectionBeanToPropertyValueTransformer和commons-collections4

Collection<MyType> myTypes = (Collection<MyType>) CollectionUtils.collect(myCollection, new BeanToPropertyValueTransformer("myProperty")) 

唯一的缺点就是泛型是不支持的,所以类型转换必须完成。

commons-collection4中运用哪种解决方案,利用泛型?

回答

1

显然他们从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"));