检查样式:如何解决“隐藏字段”错误

2022-08-31 13:37:55

我收到此检查样式错误:

'serverURL' hides a field

在这个

 private static void setServerURL(final String serverURL) {
    Utility.serverURL = serverURL;
 }

可能的原因是什么,如何解决它?


答案 1

已经定义了一个可用于此方法的变量(除了您正在接受的形式参数之外)。这称为“阴影”。serverURL

我认为大多数Java程序员都会关闭这个检查,因为它并不是那么令人困惑。

例如,这将触发错误:

public class Foo {
  private int bar = 0;

  public void someMethod(int bar) {
    // There are two bars!  All references in this method will use the parameter bar,
    // unless they are explicitly prefixed with 'this'.
    this.bar = bar;
  }
}

答案 2

我认为在构造函数和 setter 中,set 字段名称与 setter 参数名称相同是很常见的。这就是为什么我推荐这个配置:

<module name="HiddenField" >
    <property name="ignoreSetter" value="true" />
    <property name="ignoreConstructorParameter" value="true" />
</module>

这样,其他隐藏的字段案例仍然被禁止。


推荐