具有从构造函数调用的超类可覆盖方法的最终子类 - Spotbugs

Final subclass with a superclass overridable method called from constructor - 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

注:

自从 Spotbugs 4.5.0.0 添加了错误检测器 FindOverridableMethodCall(参见 详细信息 ):

MC: An overridable method is called from a constructor
(MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR)

Calling an overridable method during in a constructor may result in the use of uninitialized data. It may also leak the reference of the partially constructed object. Only static, final or private methods should be invoked from a constructor.

这似乎是一个错误,最近打开了一个与此案例相关的 issue

False positive for MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR in final class

还有一个pull request来修复这个bug。