Determining if a method overrides another at runtime

inheritance, java, overriding, reflection

Solution

You can simply cross-check method names and signatures.

public static boolean isOverriden(Method parent, Method toCheck) {
    if (parent.getDeclaringClass().isAssignableFrom(toCheck.getDeclaringClass())
            && parent.getName().equals(toCheck.getName())) {
         Class<?>[] params1 = parent.getParameterTypes();
         Class<?>[] params2 = toCheck.getParameterTypes();
         if (params1.length == params2.length) {
             for (int i = 0; i < params1.length; i++) {
                 if (!params1[i].equals(params2[i])) {
                     return false;
                 }
             }
             return true;
         }
    }
    return false;
}

However, since your goal is to rename methods, you might instead wish to use a bytecode analysis/manipulation library such as ASM, where you can perform the same tests as well as easily modify the methods' names if the method returns true.

Problem

I was wondering if there was any way to determine if a method represented by given `java.lang.Method` object overrides another methods represented by another `java.lang.Method` object? I'm working on Stronlgy typed javascript, and I need to be able to be able to know if a method overrides another one in order to be able to rename both of them to a shorter name. In this case, I am talking about the extended definition of overriding, as supported by the `@Override` annotation, which includes implementation of interface and abstract class methods. I'd be happy with any solution involving either reflection directly, or using any library that already does this.

Original source