Search code examples
javaoopoptimizationmethodsoverriding

How to quickly determine if a method is overridden in Java


There is a possible optimization I could apply to one of my methods, if I can determine that another method in the same class is not overridden. It is only a slight optimization, so reflection is out of the question. Should I just make a protected method that returns whether or not the method in question is overridden, such that a subclass can make it return true?


Solution

  • I wouldn't do this. It violates encapsulation and changes the contract of what your class is supposed to do without implementers knowing about it.

    If you must do it, though, the best way is to invoke

    class.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. Yes, this is reflection, but it's still pretty cheap.

    I do like your protected-method approach, though. That would look something like this:

    public class ExpensiveStrategy {
      public void expensiveMethod() {
        // ...
        if (employOptimization()) {
          // take a shortcut
        }
      }
    
      protected boolean employOptimization() {
        return false;
      }
    }
    
    public class TargetedStrategy extends ExpensiveStrategy {
      @Override
      protected boolean employOptimization() {
        return true; // Now we can shortcut ExpensiveStrategy.
      }
    }