调用超级超类方法 [英] Calling super super class method

查看:83
本文介绍了调用超级超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆