Java 如何强制派生类调用超级方法?(就像安卓一样)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4217013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force derived class to call super method? (Like Android does)
提问by Peterdk
I was wondering, when creating new Activity
classes and then overriding the onCreate()
method, in eclipse I always get auto added: super.onCreate()
. How does this happen? Is there a java keyword in the abstract or parent class that forces this?
我想知道,在创建新Activity
类然后覆盖该onCreate()
方法时,在 Eclipse 中我总是自动添加:super.onCreate()
. 这是怎么发生的?抽象类或父类中是否有强制执行此操作的 java 关键字?
I don't know if it is illegal not to call the super class, but I remember in some methods that I got a exception thrown for not doing this. Is this also built-in into java? Can you use some keyword to do that? Or how is it done?
我不知道不调用超类是否违法,但我记得在某些方法中我因为不这样做而抛出异常。这也内置在java中吗?你能用一些关键字来做到这一点吗?或者是怎么做的?
采纳答案by Matt Ball
Here's the source of Activity#onCreate()
- it is almost all comments (original - see line ~800):
这是的来源Activity#onCreate()
- 它几乎是所有评论(原始 - 见行 ~800):
/**
* Called when the activity is starting. This is where most initialization
* should go: calling {@link #setContentView(int)} to inflate the
* activity's UI, using {@link #findViewById} to programmatically interact
* with widgets in the UI, calling
* {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
* cursors for data being displayed, etc.
*
* <p>You can call {@link #finish} from within this function, in
* which case onDestroy() will be immediately called without any of the rest
* of the activity lifecycle ({@link #onStart}, {@link #onResume},
* {@link #onPause}, etc) executing.
*
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
*
* @see #onStart
* @see #onSaveInstanceState
* @see #onRestoreInstanceState
* @see #onPostCreate
*/
protected void onCreate(Bundle savedInstanceState) {
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mCalled = true;
}
so, my guess would be that the ADT Eclipse plugin is what's auto-adding that call to super.onCreate()
for you. It's a total guess, though.
所以,我的猜测是 ADT Eclipse 插件会自动super.onCreate()
为您添加该调用。不过,这完全是猜测。
回答by DJClayworth
There is nothing in Java that forces calling of super, and there are plenty of examples when you wouldn't want to. The only place where you can force calling of super is in constructors. All constructors have to call a superclass constructor. One (the no arguments constructor) will be inserted if you don't write one explicitly, and if there is no no-arguments constructor then you must call it explicitly.
Java 中没有任何东西可以强制调用 super,并且有很多您不想调用的示例。唯一可以强制调用 super 的地方是在构造函数中。所有构造函数都必须调用超类构造函数。如果您不显式编写一个(无参数构造函数),则将插入一个(无参数构造函数),如果没有无参数构造函数,则必须显式调用它。
回答by hvgotcodes
Eclipse is just being helpful, reminding you that you can call the superclass implementation if you want.
Eclipse 只是很有帮助,提醒您可以根据需要调用超类实现。
you are probably getting an error because you are not doing something necessary that the superclass does, since you are not calling its implementation.
您可能会收到错误消息,因为您没有执行超类所做的必要操作,因为您没有调用它的实现。
回答by Lagerbaer
If you want to make absolutely sure that the superclass-method is called as well, you must trick a bit: Don't allow the superclass-method to be overwritten, but have it call an overridable protected method.
如果你想绝对确保超类方法也被调用,你必须小技巧:不要让超类方法被覆盖,而是让它调用一个可覆盖的受保护方法。
class Super
{
public final void foo() {
foo_stuff();
impl_stuff();
}
protected void impl_stuff() {
some_stuff_that_you_can_override();
}
}
class Base extends Super
{
protected void impl_stuff() {
my_own_idea_of_impl();
}
}
That way, the user must call Super.foo() or Base.foo() and it will always be the base-class version as it was declared as final. The implementation-specific stuff is in impl_stuff(), which can be overriden.
这样,用户必须调用 Super.foo() 或 Base.foo() 并且它将始终是基类版本,因为它被声明为最终版本。特定于实现的东西在 impl_stuff() 中,它可以被覆盖。
回答by Andrzej Doyle
If you want to forcesubclasses to execute the parent class' logic, a common pattern is something like the following:
如果你想强制子类执行父类的逻辑,一个常见的模式是这样的:
public abstract class SuperClass implements SomeInterface
{
// This is the implementation of the interface method
// Note it's final so it can't be overridden
public final Object onCreate()
{
// Hence any logic right here always gets run
// INSERT LOGIC
return doOnCreate();
// If you wanted you could instead create a reference to the
// object returned from the subclass, and then do some
// post-processing logic here
}
protected abstract Object doOnCreate();
}
public class Concrete extends SuperClass
{
@Override
protected Object doOnCreate()
{
// Here's where the concrete class gets to actually do
// its onCreate() logic, but it can't stop the parent
// class' bit from running first
return "Hi";
}
}
This doesn't actually answer your question about what prompts Eclipse to automatically insert a superclass call into the implementation; but then I don't think that's the way to go anyway as this can always be deleted.
这实际上并没有回答您关于什么提示 Eclipse 自动将超类调用插入到实现中的问题;但后来我认为这不是要走的路,因为它总是可以被删除。
You can't actually enforce that a method must call the superclass' version with a Java keyword, or anything like that. I suspect that your exceptions simply came from some code in the parent class checking expected invariants, or something, that were invalidated by your approach. Note that this is subtly different from throwing an exception becauseyou failed to call super.onCreate()
.
您实际上无法强制方法必须使用 Java 关键字或类似关键字调用超类的版本。我怀疑您的异常只是来自父类中的某些代码,检查预期的不变量或其他东西,这些代码被您的方法无效。请注意,这与抛出异常有细微的不同,因为您未能调用super.onCreate()
.
回答by Flygenring
Eclipse just helps you doing things right and avoid exceptions.
Eclipse 只是帮助您正确地做事并避免异常。
From http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)
来自http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
派生类必须调用该方法的超类实现。如果他们不这样做,将引发异常。
回答by speakingcode
To answer your actual question, the auto-creation of the call to super.onCreate() is a feature of the ADT plugin. In java, you cannot directly force a subclass to call the super implementation of a method, afaik (see the pattern described in other answers for work-around). However, keep in mind that in Android, you are not instantiating Activity objects (or Service objects) directly - you pass an Intent to the system and the system instantiates the object and calls onCreate() upon it (along with other lifecycle methods). So the system has a direct object reference to the Activity instance and is able to check (presumably) some Boolean that is set to true in the superclass implementation of onCreate(). Although I don't know exactly how it is implemented, it probably looks something like this:
为了回答您的实际问题,自动创建对 super.onCreate() 的调用是 ADT 插件的一项功能。在 java 中,您不能直接强制子类调用方法 afaik 的超级实现(请参阅其他答案中描述的模式以获取解决方法)。但是,请记住,在 Android 中,您不会直接实例化 Activity 对象(或 Service 对象)——您将 Intent 传递给系统,系统会实例化该对象并对其调用 onCreate()(以及其他生命周期方法)。因此,系统具有对 Activity 实例的直接对象引用,并且能够检查(大概)在 onCreate() 的超类实现中设置为 true 的一些布尔值。虽然我不知道它是如何实现的,但它可能看起来像这样:
class Activity
{
onCreate()
{
superCalled = true;
...
}
...
}
And in the "system" level class that receives the Intent and instantiates the Activity object from it:
在接收 Intent 并从中实例化 Activity 对象的“系统”级类中:
...
SomeActivitySubclass someActivitySubclassObject = new SomeActivitySubclass();
someActivitySubclassObject.onCreate();
if (!someActivityObject.isSuperCalled())
{
Exception e = new Exception(...) //create an exception with appropriate details
throw e;
}
My guess is it's probably slightly more complex than that, but you get the idea. Eclipse automatically creates the call because the ADT plugin tells it to, as a convenience. Happy coding!
我的猜测是它可能比这稍微复杂一些,但你明白了。为方便起见,Eclipse 会自动创建调用,因为 ADT 插件告诉它。快乐编码!
回答by runor49
This is added in the support annotation library:
这是在支持注释库中添加的:
dependencies {
compile 'com.android.support:support-annotations:22.2.0'
}
http://tools.android.com/tech-docs/support-annotations
http://tools.android.com/tech-docs/support-annotations
@CallSuper
@CallSuper