java - Sonar 问题 "Method parameters, caught exceptions and foreach variables should not be reassigned"

标签 java sonarqube

我的代码进行了 SONAR 扫描,但出现了一个重大错误,指出“不应重新分配方法参数、捕获的异常和 foreach 变量”。我不明白他们是如何被重新分配的。他们能解决这个问题吗?我收到错误消息“reportForm = new ReportForm();”在下面的代码中。

 public ModelAndView getPcVolumeTopOffendersShortpaid(@Valid @ModelAttribute("reportForm") ReportForm reportForm, BindingResult result) {
    // Handle invalid request date cleanly ...
    // when invalid or doesn't exist, use the current date for selection
    // otherwise, selection is valid and can be used in criteria for query
    if (reportForm == null || result.hasErrors()) {
        reportForm = new ReportForm();
        reportForm.setMonthYear(DateFormatterUtil.getAbbreviatedMonthYearFromCurrentDateTime());
    }

    // Create the criteria for the specified, and retrieve the report
    reportForm.setReportType(ReportType.SHORTPAID_TOP_OFFENDERS_BY_VOLUME);
    TopOffendersReportCriteria topOffendersReportCriteria = reportService.getTopOffendersReportCriteria(reportForm);
    List<TopOffendersReport> list = reportService.getTopOffendersReport(topOffendersReportCriteria);

    // Return the reports view and the supporting page objects
    ModelAndView mv = new ModelAndView("reports/topOffendersShortpaidVolume");
    mv.addObject("reportList", list);
    mv.addObject("reportForm", reportForm);
    return mv;
}

最佳答案

在提到的行中

reportForm = new ReportForm();

reportForm 是方法参数。意味着它仅在本地可见。如果 reportForm 引用了某个作为参数传递给此行的对象,您将通过指向另一个对象而丢失此引用。而且很可能您想做其他事情。方法完成后,新创建的对象将丢失。

如果您想将对象创建委托(delegate)给您的方法 - 它不会起作用。

关于java - Sonar 问题 "Method parameters, caught exceptions and foreach variables should not be reassigned",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992803/

相关文章:

gradle - SonarQube,JaCoCo :(应该是22个条件中的11个)应该是3个(或4个)

php - Sonar 分析PHP项目的问题

sonarqube - 尽管有登录凭据,Sonarqube 项目细节仍被披露

java - 如何打印带有完整年份和数字前零的本地化日期?

java - PrimeFaces DataTable - 过滤(运行示例的问题)

sonarqube - 尽管添加了新插件,如何让质量门通过?

java - "Method foo() needlessly boxes a boolean constant" Sonar 警告

java - 如何使用 Stream 拆分集合中的奇数和偶数以及两者的总和

java - 使用 dom4j 添加命名空间和命名空间前缀

java - Android 主页按钮、计时器问题