[英]Call super without super keyword java
Im developing Android Application and somehow I should call "super" without super keyword inside method.我正在开发 Android 应用程序,不知何故我应该在方法内部没有 super 关键字的情况下调用“super”。 Can I call super with instance of class?
我可以用类的实例调用 super 吗? For example:
例如:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
How can I call super.onCreate(savedInstanceState) without using super keyword?如何在不使用super关键字的情况下调用super.onCreate(savedInstanceState) ?
UPDATE 1 I tried this but this is not working too.更新 1我试过这个,但这也不起作用。
@Override
public void onCreate(Bundle savedInstanceState) {
try {
getClass().getSuperclass().getMethod("onCreate",Bundle.class).invoke(this,savedInstanceState);
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Note: Please understand what I'm talking about.注意:请理解我在说什么。 Don't say 'call super()'.
不要说“调用 super()”。
Not calling super
methods is generally a very bad idea, especially when it comes to the activity lifecycle.不调用
super
方法通常是一个非常糟糕的主意,尤其是在涉及 Activity 生命周期时。 In fact, an activity will crash without fail if the super
method of an activity lifestyle event is not called.实际上,如果不调用 Activity 生活方式事件的
super
方法,则 Activity 肯定会崩溃。
By using @Override
on a method, you are amending its functionality to do tasks you require, ie declare views.通过在方法上使用
@Override
,您正在修改其功能以执行您需要的任务,即声明视图。 However, the parent class may need to do other important things that are of no concern to app-level developers ie set states or flags.然而,父类可能需要做应用级开发人员不关心的其他重要事情,即设置状态或标志。 If a method was designed to be completely implemented by an app-level developer without any parent code executed, it would be declared
abstract
or part of an interface
instead.如果一个方法被设计为完全由应用程序级开发人员实现而不执行任何父代码,那么它将被声明为
abstract
或interface
一部分。
Further reading:进一步阅读:
public class A {
static void m1() {
System.out.println("m1 P");
}
}
class B extends A {
static void m1() {
System.out.println("m1 C");
}
}
class Test {
public static void main(String[] args) {
A a = new B();
A.m1();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.