避免'未经检查的电话'警告

时间:2017-10-25 19:04:44

标签: java generics

假设我有方法getTransformer(Item item)的工厂界面 Item是一个界面。 Factory使用instanceOf为Item to Entity找到正确的变换器。 Transformer实现方法S transform(T item)

呼叫工厂以获得变压器是可以的,但是在IDE中突出显示呼叫transformer.transform作为对transform(T)的未经检查的呼叫。怎么避免这个? 即

DTOTransformer dtoTransformer = dtoTransformerFactory.getTransformer(item);
ItemEntity itemEntity = dtoTransformer.transform(item); // this line has error
顺便说一句,这是我即将面试的一篇文章。我想知道这是否可以修复,或者只是使用注释未选中以避免编译器警告。

public interface DTOTransformer<S extends ItemEntity, T extends Item> {

    S transform(T item);
}

public interface DTOTransformerFactory {

    DTOTransformer getTransformer(Item item);
}

public class DTOTransformerFactoryImpl implements DTOTransformerFactory {
    @Override
    public DTOTransformer getTransformer(Item item) {
        if (item instanceof RegularItemDTO) {
            return new RegularDTOTransformer();
        } else if (item instanceof SpecialItemDTO) {
            return new SpecialDTOTransformer();
        } else {
            throw new IllegalArgumentException("No transformer for type:     " + item.getClass());
        }
    }
}

public class SpecialDTOTransformer implements     DTOTransformer<SpecialItemEntity, SpecialItemDTO> {
    @Override
    public SpecialItemEntity transform(SpecialItemDTO item) {
        SpecialItemEntity specialItemEntity = new SpecialItemEntity();
        specialItemEntity.setPrice(item.getPrice());
        specialItemEntity.setSku(item.getSku());
        specialItemEntity.setItem(item.getItem());
        specialItemEntity.setBuyAmount(item.getBuyAmount());
        specialItemEntity.setDiscountPrice(item.getDiscountPrice());

        return specialItemEntity;
    }
}

1 个答案:

答案 0 :(得分:0)

dtoTransformer没有类型参数,因此它具有原始类型。

您需要向工厂添加一些类型参数:

public interface DTOTransformerFactory {
    DTOTransformer<?, Item> getTransformer(Item item);
               // ^-------^ Here
}

public class DTOTransformerFactoryImpl implements DTOTransformerFactory {
    @Override
    public DTOTransformer<?, Item> getTransformer(Item item) {
                      // ^-------^ Here
        if (item instanceof RegularItemDTO) {
            return new RegularDTOTransformer<>();
                                         // ^^ Here, assuming RegularDTOTransformer is similarly parametrized.
        } else if (item instanceof SpecialItemDTO) {
            return new SpecialDTOTransformer<>();
                                         // ^^ Here.
        } else {
            throw new IllegalArgumentException("No transformer for type:     " + item.getClass());
        }
    }
}

然后:

DTOTransformer<?, Item> dtoTransformer = dtoTransformerFactory.getTransformer(item);
ItemEntity itemEntity = dtoTransformer.transform(item); // this line has error