简体   繁体   中英

Final subclass with a superclass overridable method called from constructor - Spotbugs 4.5.0.0

If a final subclass calls a superclass overridable method from the constructor, Spotbugs reports a bug (see note below for details).

Is this expected or is it an issue?

For example:

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;
    }

}

Reports:

[ERROR] Low: Overridable method getId is called from constructor new SubClass(int, String).
[SubClass] At SubClass.java:[line ?] MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR

Note:

Since Spotbugs 4.5.0.0 bug detector FindOverridableMethodCall was added (see details ):

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.

This seems to be a bug, there is a recent open issue related to this case:

False positive for MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR in final class

There is also a pull request to fix this bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM