EL_9
EL_9

Reputation: 414

Java getMethods() with respect to inheritance hirarchy

What I eventually want to do is to invoke all methods that have some annotation in a way such that:

  1. Overridden methods will be invoked only once.

  2. 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.

Is there a way to get the methods sorted in such way?

Upvotes: 2

Views: 136

Answers (1)

Mureinik
Mureinik

Reputation: 311188

You could create a Comparator that sorts the Method objects according to the class that declared them:

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;
    }
}

And then use it to sort the Method objects you have. E.g.:

Method[] methods = // All the relevant methods...
Arrays.sort(methods, new MethodInheritanceComparator());

Note that Class#getMethods only returns one Method object in the case of an overridden method, so your first requirement is fulfilled "out of the box".

Upvotes: 2

Related Questions