最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

PMD笔记-Overridable method 'XXX' called during object construction

互联网 admin 1浏览 0评论

PMD笔记-Overridable method 'XXX' called during object construction

PMD错误

Overridable method ‘XXX’ called during object construction

样例

public class Test {
    public int a;

    public Test() {
        test();
    }

    public void test() {
        a = 10;
    }
}

报错原因

不要在构造方法里调用可被重写的方法,这会导致构造方法的行为不定。虽然在编译期时没有异常,但是在运行期时可能发生异常。

详细的分析可以参考Java中不要在父类的构造方法中调用会被子类重写的方法

解决方法

有两个方法:
1.将该方法加上final

public class Test {
    public int a;

    public Test() {
        test();
    }

    public final void test() {
        a = 10;
    }

2.将该方法改为private

public class Test {
    public int a;

    public Test() {
        test();
    }

    private void test() {
        a = 10;
    }

PMD笔记-Overridable method 'XXX' called during object construction

PMD错误

Overridable method ‘XXX’ called during object construction

样例

public class Test {
    public int a;

    public Test() {
        test();
    }

    public void test() {
        a = 10;
    }
}

报错原因

不要在构造方法里调用可被重写的方法,这会导致构造方法的行为不定。虽然在编译期时没有异常,但是在运行期时可能发生异常。

详细的分析可以参考Java中不要在父类的构造方法中调用会被子类重写的方法

解决方法

有两个方法:
1.将该方法加上final

public class Test {
    public int a;

    public Test() {
        test();
    }

    public final void test() {
        a = 10;
    }

2.将该方法改为private

public class Test {
    public int a;

    public Test() {
        test();
    }

    private void test() {
        a = 10;
    }
发布评论

评论列表 (0)

  1. 暂无评论