如果是像下面这样复杂的继承层次结构,
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() 的最后一次重写发生在“H”类中。鉴于每个级别都有太多的类、抽象类和接口(interface)实现,您可以理解方法重载的复杂性和数量以及每个类所承载的功能量。手动执行并找出答案总是很困难:(
问题,
- Java 中是否有任何东西,给定一个对象和一个函数作为输入,并告诉我哪个类覆盖了层次结构中最后一个函数。
例如,
For => A a = new J();我需要将“H”类作为输出
For => A a = new F();我需要将“D”类作为输出
最佳答案
找到了更好的方法
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() 返回最新重写的类名。
关于java - 如何在复杂的继承层次结构中找到哪个类重写了某个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56145617/