Chu*_*ang 3 java generics transformer-model apache-commons-collection
嗨,我正在使用commons集合泛型4.01.
我有一个dto对象.
Class PricingDto {
private Double tax;
private Double price;
private Double tip;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我有一份清单 List<PricingDto> pricingDtos = this.pricingService.getAllPricings();
比我有一个私人静态类.
import org.apache.commons.collections15.Transformer;
import org.apache.commons.collections15.list.TransformedList;
class TotalServiceImpl implements TotalService {
public static final PricingDtoTransformer PRICING_DTO_TRANSFORMER =
new PricingDtoTransformer();
private static class PricingDtoTransformer
implements Transformer<PricingDto, Double> {
public PricingDtoTransformer() {}
@Override
public Double transform(final PricingDto pricingDto) {
return pricingDto.getTax()
+ pricingDto.getPrice()
+ pricingDto.getTips();
}
}
@Override
public List<Double> getListDouble(final List<PricingDto> pricingDtos) {
final List<Double> totalList =
TransformedList.decorate(pricingDtos, PRICING_DTO_TRANSFORMER);
for (Double d : totalList) {
// print them.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我得到类强制转换异常,因为totalList中的每个项目都是PricingDto而不是Double.
2.)我做错了什么.什么是为generics commons-collections实现自定义变换器的正确方法.
该Javadoc中明确指出:
如果列表中已有任何元素被装饰,则不会对它们进行转换.
请尝试以下方法:
CollectionUtils.transform(pricingDtos, PRICING_DTO_TRANSFORMER);
Run Code Online (Sandbox Code Playgroud)
这将通过将Transformer应用于每个元素来转换集合.