繁体   English   中英

如何在 Java/eclipse 中添加不调用 super() 的警告

[英]how to add a warning for not calling super() in Java/eclipse

我希望子类总是为某些方法调用 super()。 如何在编译时强制执行或至少发出警告?

谢谢

您可以稍微不同地设计它以强制执行该行为:

超类应该是抽象的,或者至少定义 final 方法。 然后定义子类必须实现的受保护方法,并在完成任何需要预先运行的代码后,最终让超类调用该方法:

public abstract class SuperClass {
    // final so it can't be overriden
    public final void superMethod() {
        // required code here

        // then delegate to implMethod
        implMethod();
    }

    protected abstract() void implMethod();
}

public class SubClasss extends SuperClass {
    protected void implMethod() {
        // sub class logic
    }
}

当然,SuperClass 不一定是抽象的,你可以实现 implMethod 然后允许子类覆盖它

我认为Chris White的回答在一般情况下是最好的。 但是陈英的评论“我知道强制调用super不好。但我没有拥有超类。SDK文档要求调用super。例如link”表明它不适合这种特殊情况。

因此,我建议修改 Chris White 的答案以满足细节。

class ChenYingTestCase extends ServiceTestCase
{
       /**
        * Gets the current system context and stores it.
        * You can not extend this method.
        * If you want to achieve the effect of extending this method,
        * you must override chenYingSetupMethod.
        **/
       public final void setUp ( )
       {
             super.setUp ( ) ;
             chenYingSetup ( ) ;
       }

       /**
        * Does nothing (unless you extend it)
        *
        * Extend this method to do your 
        * own test initialization. If you do so, there is no need to call super.setUp() 
        * Hint:  calling super.setUp() is probably a bad idea.
        * as the first statement in your override.
        * Just put your test initialization here.
        * The real SetUp method will call super.setUp() and then this method.
        **/
       protected void chenYingSetUp ( )
       {
       }
}

然后,如果子类在您的控制之下,则将其设为 ChenYingTestCase 的子类。 如果子类不在您的控制之下,那么您就不能真正强迫它调用 super()。

时间长了,东西变了。 现在(将近 9 年后)有一个@CallSuper注释,您可以添加基本方法以确保任何覆盖此方法的类都必须调用super 请参阅此处了解更多信息。

如果基类具有默认(无参数)构造函数,则在未给出显式 super() 调用的情况下,它将始终自动调用。 如果您可以控制基类,则可以将默认构造函数设为私有:

public abstract class Whatever {
    private Whatever() {
        // not visible to subclasses
    }

    public Whatever(A a, B b, ...) {
        // this constructor must always be explicitly called by subclasses
    }
}

除此之外,您的 IDE 可能允许您为此打开警告。 它会在选项菜单中的某个地方。 如果你没有看到它,它就不存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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