【发布时间】:2020-11-26 08:11:04
【问题描述】:
我已经搜索了很多时间,但找不到解决此问题的方法。在我的春季申请中,我有一个BesoinPoseMapper
@FunctionalInterface
@Mapper(uses = BesoinPoseTranslator.class)
public interface BesoinPoseMapper {
@Mappings({
@Mapping(target = "nbCapteurs", source = "valeur", qualifiedByName = {"BesoinPoseTranslator", "nbCapteurs"}),
@Mapping(target = "typologie", source = "typologie", qualifiedByName = {"BesoinPoseTranslator", "typologie"}),
@Mapping(target = "site", source = "site", qualifiedByName = {"BesoinPoseTranslator", "emplacement"})
})
BesoinPoseDTO entityToDTO(BesoinPoseEntity entity);
}
将BesoinPoseEntity 映射到BesoinPoseDTO
但是BesoinPoseController中的map函数
public class BesoinPoseController {
@Setter
@Autowired
private BesoinPoseRepository besoinPoseRepo;
@GetMapping()
public List<BesoinPoseDTO> getBesoinsPose(@RequestParam String range, @RequestParam(required = false) String status){
return StreamSupport.stream(besoinPoseRepo.findAll().spliterator(), false)
.map(BesoinPoseMapper::entityToDTO)
.collect(Collectors.toList());
}
}
引发编译错误
.map(BesoinPoseMapper::entityToDTO);
^
required: Function<? super BesoinPoseEntity,? extends R>
found: BesoinPose[...]ToDTO
reason: cannot infer type-variable(s) R
(argument mismatch; invalid method reference
cannot find symbol
symbol: method entityToDTO(BesoinPoseEntity)
location: interface BesoinPoseMapper)
where R,T are type-variables:
R extends Object declared in method <R>map(Function<? super T,? extends R>)
T extends Object declared in interface Stream
我尝试使用 lambda 并将类型从可迭代更改为列表和数组,然后再返回到流,但无济于事,错误仍然存在。编译器无法推断出 R 类型是 BesoinPoseDTO。
有没有办法解决这个问题?
谢谢
【问题讨论】:
-
我认为您需要一个
BesoinPoseMapperread this 的实例 -
当您使用
.map(BesoinPoseMapper::entityToDTO)时,编译器将尝试在您的流元素类型上查找entityToDTO()(在这种情况下,只有当besoinPoseRepo.findAll()返回的对象类型为BesoinPoseMapper的子类 - 除非BesoinPoseMapper.entityToDTO是静态的。显然,情况并非如此。正如 YCF_L 所说,您可能打算拥有BesoinPoseMapper的实例并使用.map(myBesoinPoseMapperInstance::entityToDTO)
标签: java spring java-stream