How to quickly determine if a method is overridden in Java

Well, my optimization is a small yield on a case-by-case basis, and it only speeds things a lot because it is called hundreds of times per second.

You might want to see just what the Java optimizer can do. Your hand-coded optimization might not be necessary.

If you decide that hand-coded optimization is necessary, the protected method approach you described is not a good idea because it exposes the details of your implementation.


How many times do you expect the function to be called during the lifetime of the program? Reflection for a specific single method should not be too bad. If it is not worth that much time over the lifetime of the program my recommendation is to keep it simple, and don't include the small optimization.

Jacob


Annotate subclasses that overrides the particular method. @OverridesMethodX.

Perform the necessary reflective work on class load (i.e., in a static block) so that you publish the information via a final boolean flag. Then, query the flag where and when you need it.


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.
  }
}