如何找到哪个 class 覆盖了复杂继承层次结构中的函数?
How to find which class has overridden a function in a complex inheritance hierarchy?
如果像下面这样的复杂继承层次结构,
A 有一个函数名 whoOverrideMeLatest();
A {Interface}
|
B {Interface}
|
C {abstract class} {implemented whoOverrideMeLatest()}
|
D {abstract class extending C and implementing some random 5 interfaces} {overrides whoOverrideMeLatest()}
|
E {concrete class}
|
F {concrete class}
|
G {G is abstract class which extends F and implements 10 other interfaces}
|
H {concrete class and overrides whoOverrideMeLatest()}
|
I {abstract class extending H and implementing 3 interfaces}
|
J {concrete class}
假设如果我按以下方式创建 J 的实例,
A a = new J();
如您所见,函数 whoOverrideMeLatest() 的最后一次覆盖发生在 class "H" 中。鉴于每一层都有太多的 class、抽象 class 和接口实现,你可以理解方法重载的复杂性和体积以及每个 class 携带的函数数量。手动完成并找出答案总是很困难:(
问题,
- 在给定一个对象和一个函数作为输入的情况下,Java 中是否有任何内容告诉我哪个 class 覆盖了层次结构中最后一个函数。
例如,
For => A a = new J();我需要得到 class "H" 作为输出
For => A a = new F();我需要得到 class "D" 作为输出
您可以只对 A 的对象调用 whoOverrideMeLatest。它将调用层次结构中最后一个函数。这就是所谓的多态性。当然,您必须在所有应该实现 whoOverrideMeLatest 的具体 类 中实现 whoOverrideMeLatest。
class E extends D{
whoOverrideMeLatest (){
System.out.println("E");
}
}
找到了更好的方法,
Found a better way to do it,
A a= new J();
Method[] methods = a.getClass().getMethods();
for(Method method : methods) {
System.out.println(method.getDeclaringClass() + " " + method.getName());
}
method.getDeclaringClass() returns 最新覆盖的 class 名称。
如果像下面这样的复杂继承层次结构,
A 有一个函数名 whoOverrideMeLatest();
A {Interface}
|
B {Interface}
|
C {abstract class} {implemented whoOverrideMeLatest()}
|
D {abstract class extending C and implementing some random 5 interfaces} {overrides whoOverrideMeLatest()}
|
E {concrete class}
|
F {concrete class}
|
G {G is abstract class which extends F and implements 10 other interfaces}
|
H {concrete class and overrides whoOverrideMeLatest()}
|
I {abstract class extending H and implementing 3 interfaces}
|
J {concrete class}
假设如果我按以下方式创建 J 的实例,
A a = new J();
如您所见,函数 whoOverrideMeLatest() 的最后一次覆盖发生在 class "H" 中。鉴于每一层都有太多的 class、抽象 class 和接口实现,你可以理解方法重载的复杂性和体积以及每个 class 携带的函数数量。手动完成并找出答案总是很困难:(
问题,
- 在给定一个对象和一个函数作为输入的情况下,Java 中是否有任何内容告诉我哪个 class 覆盖了层次结构中最后一个函数。
例如,
For => A a = new J();我需要得到 class "H" 作为输出
For => A a = new F();我需要得到 class "D" 作为输出
您可以只对 A 的对象调用 whoOverrideMeLatest。它将调用层次结构中最后一个函数。这就是所谓的多态性。当然,您必须在所有应该实现 whoOverrideMeLatest 的具体 类 中实现 whoOverrideMeLatest。
class E extends D{
whoOverrideMeLatest (){
System.out.println("E");
}
}
找到了更好的方法,
Found a better way to do it,
A a= new J();
Method[] methods = a.getClass().getMethods();
for(Method method : methods) {
System.out.println(method.getDeclaringClass() + " " + method.getName());
}
method.getDeclaringClass() returns 最新覆盖的 class 名称。