[英]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. 我总是得到T
和R
是未知的……似乎错过了一些东西。
Start with adding T
and R
type parameters to your generic method. 首先将T
和R
类型参数添加到您的通用方法中。 However, this will not do the trick, because convertToDto(bean)
would remain undefined. 但是,这不会解决问题,因为convertToDto(bean)
仍未定义。
You have several options here: 您在这里有几种选择:
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.