在 Java 中以通用方式转换集合



我正在尝试将实现DomainEntity的对象集合转换为实现DomainEntityDTO的对象集合。DomainEntity 对象提供了一个方法 toDTO() 来执行转换。

这是我的代码。

public class EntityCollectionConverter<T  extends DomainEntityDTO, Y extends DomainEntity> {
    public Collection<T> convert(Collection<Y> collection){
        Collection<T> dtoList = new ArrayList<>();
        for (DomainEntity domainObject : collection) {
            DomainEntityDTO dto = domainObject.toDTO();
            dtoList.add(dto); // Compiler: "T cannot be applied to DomainEntityDTO"
        }
        return dtoList;
    }
}

dtoList.add(dto);行无法编译,因为"T 不能应用于 DomainEntityDTO"。

界面 DomainEntity 如下所示:

public interface DomainEntity {
    Long getId();
    <T extends DomainEntityDTO> T toDTO();
}

知道我哪里出错了吗?

您需要声明类型为 T 的变量。

最新更新