Is there a way to determine if a method has been overridden in a Java class

peterk :

I want to be able to determine if a base class method has been overridden by a subclass specifically because expensive setup is needed before invoking it and most subclasses in our system do not override it. Can it be tested by using reflection provided method handles? Or is there some other way to test if a class method is overridden?

e.g.

class BaseClass {
    void aMethod() { // don nothing }

    protected boolean aMethodHasBeenOverridden() {
        return( // determine if aMethod has been overridden by a subclass);
    } 
}
dasblinkenlight :

You can do it with reflection by examining the declaring class of your method:

class Base {
    public void foo() {}
    public void bar() {}
}
class Derived extends Base {
    @Override   
    public void bar() {}
}
...
Method mfoo = Derived.class.getMethod("foo");
boolean ovrFoo = mfoo.getDeclaringClass() != Base.class;
Method mbar = Derived.class.getMethod("bar");
boolean ovrBar = mbar.getDeclaringClass() != Base.class;
System.out.println("Have override for foo: "+ovrFoo);
System.out.println("Have override for bar: "+ovrBar);

Prints

Have override for foo: false
Have override for bar: true

Demo.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=426471&siteId=1