Java:Commons-Collections 泛型:如何让自定义转换器工作

标签 java generics transformer-model apache-commons-collection

您好,我正在使用 commons collections generics 4.01。

我有一个 dto 对象。

Class PricingDto {
   private Double tax;
   private Double price;
   private Double tip;

   // getters and setters
}

我有一个 List<PricingDto> pricingDtos = this.pricingService.getAllPricings(); 的列表

比我有一个私有(private)静态类。

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. 
            }
        }
    }
}

我的问题是我得到类转换异常,因为 totalList 中的每个项目都是 PricingDto 而不是 Double。

2.) 我做错了什么。为泛型公共(public)集合实现自定义转换器的正确方法是什么。

最佳答案

javadocs明确指出:

If there are any elements already in the list being decorated, they are NOT transformed.

请尝试以下操作:

CollectionUtils.transform(pricingDtos, PRICING_DTO_TRANSFORMER);

这将通过将 Transformer 应用于每个元素来转换集合。

关于Java:Commons-Collections 泛型:如何让自定义转换器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4714363/

相关文章:

java - 构建问题 Spring 3 -hibernate 3 项目

java - Jsoup:如何用Java加载更多网页内容?

c# - 需要帮助来理解这个 C# 泛型类

java - 为什么 Transformer 返回 &lt 和 &gt 而不是 < 和 >?

java - 如何保证ConcurrentHashMap的get()总是返回最新的实际值?

java - 从 PHP 到哪里去?

c# - 查找并调用通用重载方法

Swift 4 通用 where 子句错误

datatable - 在 Java 中的 Cucumber 步骤中为字段定义 Datatable 单元格中的字符串列表

python - 操作系统错误 : Can't load tokenizer