You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SonarLint泛型需指定参数提示修改无效,求助

解决SonarLint「不应使用原始类型」代码问题

你遇到的问题核心是**ResponseWrapper作为泛型类,代码中使用了无类型参数的原始形式**,绕过了编译期泛型检查,所以SonarLint触发了警告。以下是针对性的修改方案:

问题定位

代码中多处使用了原始类型ResponseWrapper:

  1. 方法返回值public ResponseWrapper update(...)未指定泛型参数
  2. var validationResponse推断的是原始类型ResponseWrapper,导致后续getData()需要强制转换,存在类型安全隐患
  3. 最后构建返回对象时,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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:20:28