java - PMD 对象构造期间调用的可覆盖方法

标签 java pmd

我有以下结构

public class parent {
    int value ; 
}

public class child extends parent {
    int childValue;
    public child(){}
    public child (int value){
          this.childValue = value ; // this line cause ConstructorCallsOverridableMethod warning during object construction
    }
}

请问如何解决这个错误?

最佳答案

PMD rule说:

Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem.

例子:

public class SeniorClass {
  public SeniorClass(){
      toString(); //may throw NullPointerException if overridden
  }
  public String toString(){
    return "IAmSeniorClass";
  }
}
public class JuniorClass extends SeniorClass {
  private String name;
  public JuniorClass(){
    super(); //Automatic call leads to NullPointerException
    name = "JuniorClass";
  }
  public String toString(){
    return name.toUpperCase();
  }
}

解决方案

删除构造函数中对可覆盖方法的任何调用或向该方法添加 final 修饰符。

关于java - PMD 对象构造期间调用的可覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504404/

相关文章:

Java - 注册应用程序的自动启动

java - 登录后重定向回页面

maven-2 - 在本地解析 Maven 中的 pmd 规则集

java - Eclipse-PMD : error while installing through eclipse market place

java - Possible null pointer dereference of 的说明和修复

intellij-idea - IntelliJ PMDPlugin 自定义规则集

java - 根据语言环境确定日期时间模式

java tomcat : how to use JOAuth properly

java - 当我在类中添加 int 属性时,代码停止工作

java - 错误等于通过 PMD 发出警告