Java: how to check if a method is overridden using reflection

I need to do some processing to determine the dependencies of the annotated JSR-330 classes using reflection.

I am fully aware of all JSR-330 compatible IoC containers such as Spring, Guice or PicoContainer. However, I need not to allow or introduce dependencies, but to identify them.

This basically means that I need to implement the JSR-330 implementation, at least when it comes to “parsing” the class.

There is one part of the JSR-330 specification, which I find a bit difficult to implement:

A method annotated with @Inject, which overrides another method annotated with @Inject, is introduced only once per injection request for an instance. A method without annotation @Inject that overrides a method annotated with @Inject will not be introduced.

This means that subclasses can redefine the auto-contract for their base class, as well as connect the injection stream (through polymorphism).

Here's my question: Given the class hierarchy, is there an easy way to check if a method is redefined in some part of the hierarchy further down the hierarchy?

The easiest way to do this in my case is recursion from a hierarchy sheet:

private List<Method> getInjectableMethods(final Class<?> clazz) {
    // recursive stop condition
    if(clazz == null) {
        return emptyList();
    }

    // recursively get injectable methods from superclass
    final List<Method> allInjectableMethods = newLinkedList(getInjectableMethods(clazz.getSuperclass()));
    final List<Method> injectableMethods = newArrayList();

    // any overridden method will be present in the final list only if it is injectable in clazz
    for (final Method method : clazz.getDeclaredMethods()) {
        removeIf(allInjectableMethods, Methods.Predicates.overriddenBy(method));
        if (isInjectable(method)) {
            injectableMethods.add(method);
        }
    }
    allInjectableMethods.addAll(injectableMethods);

    return allInjectableMethods;
}

Regarding the overriddenBy Guava-like Predicate, I would check that:

  • Class definition methods are in relation to isAssignableFrom
  • Method name matches

- O (n ^ 2) .

, - . Guava Apache Commons...

+5
1

, - , , , . IoC , ( )

IDE, AFAIUK Brite Force / ( InteliiJ IDEA )

+1

All Articles