调用超级超类方法 [英] Calling super super class method
问题描述
假设我有三个A,B和C类。
Let's say I have three classes A, B and C.
- B延伸A
- C扩展B
所有都有 public void foo()
方法定义。
现在来自C的 foo()
方法我想调用A的 foo()
方法(不是它的父B的方法,而是超级超级A的方法)。
Now from C's foo()
method I want to invoke A's foo()
method (NOT its parent B's method but the super super class A's method).
我试过 super.super。 foo();
,但它的语法无效。
如何实现这一目标?
I tried super.super.foo();
, but it's invalid syntax.
How can I achieve this?
推荐答案
您甚至无法使用反射。类似
You can't even use reflection. Something like
Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass.getMethod("foo").invoke(this);
会导致 InvocationTargetException
,因为即使如果你在superSuperClass上调用foo-Method,当你在invoke中指定this时,它仍然会使用 C.foo()
。这是因为所有Java方法都是虚方法。
would lead to an InvocationTargetException
, because even if you call the foo-Method on the superSuperClass, it will still use C.foo()
when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.
看来你需要B类的帮助(例如通过定义 superFoo(){super.foo();}
方法)。
It seems you need help from the B class (e.g. by defining a superFoo(){ super.foo(); }
method).
这就是说,如果你尝试像这个,所以给我们一些背景知识会很有帮助:为什么你需要这样做?
That said, it looks like a design problem if you try something like this, so it would be helpful to give us some background: Why you need to do this?
这篇关于调用超级超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!