为什么 Activity API 生命周期方法使用 RuntimeException 来强制子类调用超级方法?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道我是在问题提出 11 个月后才回答这个问题的。我猜测原因是无法提前确定调用super方法的顺序。例如,我可能想在调用
super.onDestroy()
之前、在super.onDestroy()
之后进行清理,甚至像下面这样混合起来:这个例子是为了争论;但我相信,如果你足够努力的话,你会遇到现实世界的例子。
使用模板设计模式很难实现这种混合排序。
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()
, aftersuper.onDestroy()
or even mix it up like follows: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.
如果您不调用超类方法,您的应用程序将无法正常工作,因此 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.