为什么 Activity API 生命周期方法使用 RuntimeException 来强制子类调用超级方法?

发布于 2024-10-23 01:25:58 字数 492 浏览 3 评论 0原文

Android 要求所有 Activity 子类从其生命周期方法中调用超级方法。如果没有调用 super 方法,则会抛出异常。为什么Android使用RuntimeException机制来强制调用super方法。为什么它不使用“模板”设计模式,以便超级方法在子方法之前自动执行。例如 onDestroy() 可以按如下方式处理:-

Class Activity{

    public void onDestroyFrmwork()
    {
            //do whatever the super onDestroy() method has to do 
            onDestroy();//this will invoke the subclass method.
    }

    public void onDestroy()
    {
        //empty. will get overridden by subclasses.
    }
}

Android requires that all Activity sub-classes invoke super methods from their lifecycle methods. An exception is thrown if the super method is not invoked. Why does Android use a RuntimeException mechanism to force super methods to be called. Why does it not use the 'Template' design pattern so that super methods get executed automatically before the child methods. For example onDestroy() can be handled as follows :-

Class Activity{

    public void onDestroyFrmwork()
    {
            //do whatever the super onDestroy() method has to do 
            onDestroy();//this will invoke the subclass method.
    }

    public void onDestroy()
    {
        //empty. will get overridden by subclasses.
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甚是思念 2024-10-30 01:25:58

我知道我是在问题提出 11 个月后才回答这个问题的。我猜测原因是无法提前确定调用super方法的顺序。例如,我可能想在调用 super.onDestroy() 之前、在 super.onDestroy() 之后进行清理,甚至像下面这样混合起来:

@Override
    protected void onDestroy() {
        // Do some initial clean-up
        preDestroy();

        //Then call super
        super.onDestroy();

        //In the end do some final clean-up
        postDestroy();

    }

这个例子是为了争论;但我相信,如果你足够努力的话,你会遇到现实世界的例子。

使用模板设计模式很难实现这种混合排序。

I know I am answering this question 11 months after it was asked. I guess the reason is that the order of calling the super method cannot be determined in advance. For example, I might want to do my clean up before calling super.onDestroy(), after super.onDestroy() or even mix it up like follows:

@Override
    protected void onDestroy() {
        // Do some initial clean-up
        preDestroy();

        //Then call super
        super.onDestroy();

        //In the end do some final clean-up
        postDestroy();

    }

This example is for the sake of argument; but I'm sure you would come across real world examples if you look hard enough.

This kind of mixed ordering would be hard to achieve using Template design pattern.

悍妇囚夫 2024-10-30 01:25:58

如果您不调用超类方法,您的应用程序将无法正常工作,因此 API 会抛出 RuntimeException 以确保您不会忘记这样做。

Your application won't work correctly if you don't call the superclass methods, so the API throws a RuntimeException to make sure you don't forget to do so.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文