Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a method overrides another at runtime

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.

like image 750
LordOfThePigs Avatar asked Aug 26 '12 20:08

LordOfThePigs


People also ask

How do we identify if a method is an overridden method?

getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.

Can an object's method be overridden with a custom implementation at runtime?

As others said, no, you can't override a method at runtime.

What is the difference between method overriding and runtime polymorphism?

Overriding is when you call a method on an object and the method in the subclass with the same signature as the one in the superclass is called. Polymorphism is where you are not sure of the objects type at runtime and the most specific method is called.

Why method overriding is runtime polymorphism?

Answer to why method overriding is called runtime polymorphism in java is because the methods get resolved at the Run-Time. In simple words, when you execute a program, the method of which class out of many will be called, if they have overridden the method.


1 Answers

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.

like image 72
FThompson Avatar answered Sep 30 '22 17:09

FThompson