【发布时间】:2021-12-31 11:59:36
【问题描述】:
如果最终子类从构造函数调用超类的可重写方法,Spotbugs 会报告错误(有关详细信息,请参阅下面的注释)。
这是预期的还是有问题的?
例如:
public class SuperClass {
private final int id;
public SuperClass(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public final class SubClass extends SuperClass {
private final String name;
public SubClass(int id, String code) {
super(id);
this.name = getId() + code; // Spotbugs repot this line as a bug
}
public final String getName() {
return name;
}
}
报告:
[ERROR] Low: Overridable method getId is called from constructor new SubClass(int, String).
[SubClass] At SubClass.java:[line ?] MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR
注意:
由于添加了Spotbugs 4.5.0.0 错误检测器FindOverridableMethodCall(参见details):
MC:从构造函数调用可覆盖的方法
(MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR)在构造函数中调用可覆盖的方法可能会导致 使用未初始化的数据。它也可能泄漏参考 部分构造的对象。只有静态的、最终的或私有的 方法应该从构造函数中调用。
【问题讨论】:
标签: java inheritance subclass spotbugs