调用超超类方法 [英] Calling super super class method
问题描述
假设我有三个班级 A、B 和 C.
- B 扩展了 A
- C 扩展了 B
都定义了一个 public void foo()
方法.
现在从 C 的 foo()
方法我想调用 A 的 foo()
方法(不是它的父 B 的方法,而是超超类 A 的方法).>
我尝试了 super.super.foo();
,但它的语法无效.我怎样才能做到这一点?
你甚至不能使用反射.类似的东西
Class superSuperClass = this.getClass().getSuperclass().getSuperclass();superSuperClass.getMethod("foo").invoke(this);
会导致InvocationTargetException
,因为即使你在superSuperClass上调用foo-Method,当你指定this"在调用.这是所有 Java 方法都是虚方法这一事实的结果.
看来您需要 B 类的帮助(例如,通过定义一个 superFoo(){ super.foo(); }
方法).
也就是说,如果您尝试这样的操作,它看起来像是一个设计问题,因此向我们提供一些背景信息会很有帮助:为什么您需要这样做?
Let's say I have three classes A, B and C.
- B extends A
- C extends B
All have a public void foo()
method defined.
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).
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);
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.
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屋!