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.
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.
As others said, no, you can't override a method at runtime.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With