带有从构造函数调用的超类可重写方法的最终子类-Spotbugs



如果最后一个子类从构造函数调用超类可重写方法,则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

注意:

由于添加了Spottbugs 4.5.0.0错误检测器FindOverridableMethodCall(见详细信息(:

MC:从构造函数调用可重写方法
(MC_overridable_method_ALL_IN_constructor(

在构造函数中调用可重写方法可能会导致未初始化数据的使用。它还可能泄露部分构建的对象。仅静态、最终或私有方法应该从构造函数中调用。

这似乎是一个错误,最近有一个与此案例相关的开放问题:

最终类中MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR为假阳性

还有一个修复此错误的pull请求。

最新更新