简体   繁体   English

通用方法,通用类型unknow

[英]Generic method, generic type unknow

I have many bean i would like to convert to Dto 我有很多想要转换为Dto的豆

In every class, i do something like 在每堂课中,我都会做类似的事情

private List<AddressDto> convertsToDto(List<Address> addresses) {

    List<AddressDto> addressesDto = new ArrayList<>();
    addresses.stream().map((address) -> convertToDto(address)).forEachOrdered((addressDto) -> {
        addressesDto.add(addressDto);
    });
    return addressesDto;

}

convertToDto would be in every class.... but for convertsToDto i will put in ta abstract class where every class will extends it and put a generic convertsToDto method with generic type convertToDto将在每个类中。

public abstract class BaseService {
    public List<T> convertsToDto(List<R> beans) {

        List<T> listDto = new ArrayList<>();
        beans.stream().map((bean) -> convertToDto(bean)).forEachOrdered((dto) -> {
            listDto.add(dto);
        });
        return listDto;
    }
}

I always get T and R is unknown... seem to miss something. 我总是得到TR是未知的……似乎错过了一些东西。

Start with adding T and R type parameters to your generic method. 首先将TR类型参数添加到您的通用方法中。 However, this will not do the trick, because convertToDto(bean) would remain undefined. 但是,这不会解决问题,因为convertToDto(bean)仍未定义。

You have several options here: 您在这里有几种选择:

  • You could define bean interface to produce its DTO, or 您可以定义bean接口以产生其DTO,或者
  • You could pass a bean-to-DTO function object. 您可以传递一个bean到DTO的函数对象。

Here is the first approach: 这是第一种方法:

interface Bean<T> {
    T convertToDto();
}
public abstract class BaseService {
    public <T,R extends Bean<T>> List<T> convertsToDto(List<R> beans) {
        return beans.stream().map((b) -> b.convertToDto()).collect(Collectors.toList());
    }
    ... // Additional methods
}

Here is the second approach: 这是第二种方法:

public abstract class BaseService {
    public <T,R> List<R> convertsToDto(List<T> beans, Function<T,R> convert) {
        return beans.stream().map((b) -> convert.apply(b)).collect(Collectors.toList());
    }
}

Your BaseService class does not define these generic types. 您的BaseService类未定义这些通用类型。

Try 
public abstract class BaseService<T, R> {
...
}

public class AddressService extends BaseService<AddressDto, Address> {
...
}

You can have a generic interface like Dto<T> for this to work. 您可以使用通用接口(例如Dto<T>来使其工作。

And you will be able to have your generic convertion method to look like this: 您将可以使您的通用转换方法如下所示:

public <T extends Dto<R>> List<T> convertsToDto(List<R> beans) {
}

Your Dto objects will be implementing the interface mapping them to the base object. 您的Dto对象将实现将它们映射到基础对象的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM