【问题标题】:Final subclass with a superclass overridable method called from constructor - Spotbugs具有从构造函数调用的超类可覆盖方法的最终子类 - Spotbugs
【发布时间】: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


    【解决方案1】:

    这似乎是一个bug,最近有一个公开的issue与这个案例相关:

    最终课程中 MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR 的误报

    还有一个pull request 来修复这个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多