SonarLint泛型需指定参数提示修改无效,求助
解决SonarLint「不应使用原始类型」代码问题
你遇到的问题核心是**ResponseWrapper作为泛型类,代码中使用了无类型参数的原始形式**,绕过了编译期泛型检查,所以SonarLint触发了警告。以下是针对性的修改方案:
问题定位
代码中多处使用了原始类型ResponseWrapper:
- 方法返回值
public ResponseWrapper update(...)未指定泛型参数 var validationResponse推断的是原始类型ResponseWrapper,导致后续getData()需要强制转换,存在类型安全隐患- 最后构建返回对象时,
ResponseWrapper.builder()也是原始类型调用
修改后的完整代码
假设ResponseWrapper的泛型定义为ResponseWrapper<T>,修改如下:
public ResponseWrapper<TerritoryDto> update(TerritoryDto territoryDto) throws IOException { // Validate the payload ResponseWrapper<TerritoryEntity> validationResponse = validateUpdatePayload(territoryDto); if (validationResponse.getCode() != HttpStatus.OK.value()) return validationResponse; TerritoryEntity territory = validationResponse.getData(); // 无需强制转换 territory.setPolygon(territoryDto.getPolygon()); var updated = territoryRepository.save(territory); var erpResponse = territoryErpClient.updateTerritory( new UpdateTerritoryBoundary(territory.getPolygon().toString()), territory.getName() ); if (erpResponse == null) { // todo - Consider sending notifications to slack about ERPNext not being reachable. } return ResponseWrapper.<TerritoryDto>builder() .code(HttpStatus.OK.value()) .message("Territory updated successfully") .data(TerritoryConverterInterface.TerritoryEntityToDtoMapper.INSTANCE.converter(updated)) .build(); }
关键修改点说明
- 方法返回值:将
ResponseWrapper改为ResponseWrapper<TerritoryDto>,明确返回的响应数据类型为TerritoryDto - 校验响应类型:将
validationResponse显式声明为ResponseWrapper<TerritoryEntity>,要求validateUpdatePayload方法同步修改返回值为ResponseWrapper<TerritoryEntity>(如果之前是原始类型) - 移除强制转换:泛型类型安全后,
validationResponse.getData()直接返回TerritoryEntity,无需强制转换 - 构建响应对象:通过
ResponseWrapper.<TerritoryDto>builder()显式指定泛型参数,避免原始类型调用
内容的提问来源于stack exchange,提问作者justrying
相关产品推荐
相关产品推荐

