简体   繁体   English

跳过继承层次的方法和超超类的调用方法

[英]Way to skip inheritance hierarchy and call method of super super class

Is there any way to skip java inheritance hierarchy and call method of super super class? 有什么方法可以跳过java继承层次结构和超超类的调用方法?

I have 3 classes in java 我在Java中有3个课程

X
Y extends X
Z extends Y.

Now is there any way to access any method of X directly skipping Y ? 现在有什么方法可以直接跳过Y来访问X的任何方法吗?

Here Why is super.super.method(); 这里为什么是super.super.method(); not allowed in Java? Java中不允许? They claim you cannot and there's a good discussion of why. 他们声称您不能这样做,并且对原因进行了很好的讨论。

edit I'm assuming you have a situation like foo() is defined in X and Y and you want to call it from X in Z 编辑我假设您遇到的情况是在X和Y中定义了foo(),并且您想从Z中的X调用它

Now is there any way to access any method of X directly skipping Y? 现在有什么方法可以直接跳过Y来访问X的任何方法吗?

Practically no, theoritically yes. 实际上不,理论上是。 Following your example: 按照您的示例:

X
Y extends X
Z extends Y.

When you call a method of Z, it will call super() which will call method of Y if any and it will call super() too, which will call method of X in the end. 当您调用Z的方法时,它将调用super() ,如果有的话,它将调用Y的方法,并且还将调用super() ,最后将调用X的方法。 I said yes, when method of Y does nothing different from X's, then it is as if it has no effect. 我说是的,当Y的方法与X的方法没有什么不同时,就好像它没有作用。 But in practice, JVM follows the inheritance hierarchy to complete the calls, bear in mind that. 但是在实践中,请记住,JVM遵循继承层次结构来完成调用。

我想您可以使用反射API ,但这有点丑陋的IMO。

是的,您可以访问X的所有方法(私有方法除外)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM