有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:CommonCollections泛型:如何让自定义转换器工作

大家好,我正在使用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();的列表

我有一个私人的静态类

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

我的问题是我得到了类cast异常,因为totalList中的每个项都是PricingDto,而不是Double

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


共 (2) 个答案

  1. # 1 楼答案

    对我来说,改变现有的藏品似乎是一个可怕的难题。我建议用Google Guava代替。它是^{}返回一个由原始列表和映射函数支持的视图,因此实际上您没有更改任何内容

    下面是您的代码:

    class TotalServiceImpl implements TotalService{
    
        private static final Function<PricingDto, Double> PRICING_DTO_TRANSFORMER =
            new PricingDtoTransformer();
    
        private static class PricingDtoTransformer implements
            Function<PricingDto, Double>{
    
            public PricingDtoTransformer(){
            }
    
            @Override
            public Double apply(final PricingDto pricingDto){
                return pricingDto.getTax() + pricingDto.getPrice()
                    + pricingDto.getTips();
            }
        }
    
        public List<Double> getListDouble(final List<PricingDto> pricingDtos){
            final List<Double> totalList =
                Lists.transform(pricingDtos, PRICING_DTO_TRANSFORMER);
            for(final Double d : totalList){
                // print them.
            }
            return totalList;
        }
    
    }
    

    Commons Collections可能也有类似的机制,但我一眼就找不到

  2. # 2 楼答案

    报告明确指出:

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

    请尝试以下方法:

    CollectionUtils.transform(pricingDtos, PRICING_DTO_TRANSFORMER);
    

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