[英]Java getMethods() with respect to inheritance hirarchy
我最終想要做的是以如下方式調用所有具有一些注釋的方法:
被覆蓋的方法只會被調用一次。
In case the class of the object is B
, and it inherits from A
which inherits from Object
, I want the methods defined in Object
with that annotation to be invoked first, then the methods in A
, and then the methods in B
.
有沒有辦法讓方法以這種方式排序?
您可以創建一個Comparator
器,根據聲明它們的 class 對Method
對象進行排序:
public static class MethodInheritanceComparator implements Comparator<Method> {
@Override
public int compare(Method m1, Method m2) {
Class<?> class1 = m1.getDeclaringClass();
Class<?> class2 = m2.getDeclaringClass();
if (class1.equals(class2)) {
return 0;
}
if (class1.isAssignableFrom(class2)) {
return -1;
}
if (class2.isAssignableFrom(class1)) {
return 1;
}
return 0;
}
}
然后使用它對您擁有的Method
對象進行排序。 例如:
Method[] methods = // All the relevant methods...
Arrays.sort(methods, new MethodInheritanceComparator());
請注意, Class#getMethods
僅在覆蓋方法的情況下返回一個Method
object,因此您的第一個要求是“開箱即用”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.