How to quickly determine if a method is overridden in Java
Solution 1
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.
}
}
Solution 2
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.
Solution 3
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
Solution 4
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.
Solution 5
I know this is a slightly old question, but for the sake of other googlers:
I came up with a different solution using interfaces.
class FastSub extends Super {}
class SlowSub extends Super implements Super.LetMeHandleThis {
void doSomethingSlow() {
//not optimized
}
}
class Super {
static interface LetMeHandleThis {
void doSomethingSlow();
}
void doSomething() {
if (this instanceof LetMeHandleThis)
((LetMeHandleThis) this).doSomethingSlow();
else
doSomethingFast();
}
private final void doSomethingFast() {
//optimized
}
}
or the other way around:
class FastSub extends Super implements Super.OptimizeMe {}
class SlowSub extends Super {
void doSomethingSlow() {
//not optimized
}
}
class Super {
static interface OptimizeMe {}
void doSomething() {
if (this instanceof OptimizeMe)
doSomethingFast();
else
doSomethingSlow();
}
private final void doSomethingFast() {
//optimized
}
void doSomethingSlow(){}
}
bgw
Updated on June 17, 2020Comments
-
bgw almost 4 years
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?
-
bgw about 14 yearsIt is a very commonly called method.
-
bgw about 14 yearsWell, 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. With reflection, that yield would be reduced to such a point that the optimization is pointless. A good answer, so I'm upvoting this anyways.
-
vickirk about 14 yearsIf you really really need it you could determine if the method(s) are overloaded via in a static initialiser and store the result in a boolean. Alternatively you could add this via aspectj
-
Noel Ang about 14 yearsUse Class.getMethod instead. Class.getDeclaredMethod will raise NoSuchMethodException if you ask about an inherited method that the the subclass does not override. Of course, you could use the exception as an (poor) indicator that the method wasn't overriden.
-
John Feminella about 14 years@vickirk: Static caching wouldn't work. The superclass doesn't know (without reflection) what subclass is invoking it, so it can't cache the result. If a different subclass invokes it later, that cached result will be wrong.
-
bgw about 14 yearsstatic blocks break inheritance.
-
Brett about 14 years@PiPeep: The actual instance is irrelevant. As I say, map key based upon the runtime class.
-
bgw about 14 yearsNoel: Not only is that reflection, but try...catch blocks are slow too.
-
Noel Ang about 14 yearsI know it smells. But the optimization you want is already subverting polymorphism.
-
Noel Ang about 14 yearsPiPeep: But you're resolving the decision once and for all, when the class is loaded. The computation is front-loaded.
-
Ilia Hadzhiev about 14 yearsLet me clarify my answer. I was suggesting that if you have this common pattern, and the instances are all of the same type, you could cache the value of the reflection that is performed once. You determine the configuration the first time, and use that value throughout. This way, the reflection overhead would be one time and the calls would be a much larger number. If this is called repeatedly on each instance, an instance variable declared in the parent class and lazy initialized on the first call (using reflection) might give you a boost.
-
vickirk about 14 years@John Feminella: I didn't mean add it to the superclass, just the derived classes, this is potentially a lot of code, hence my suggestion to use aspectj. If you put it in the super class the code would never get looked at. Having said that I would not do any of this
-
vickirk about 14 years+1 Seems good advice to me, don't know why it was down voted.
-
Adriano Repetti over 10 yearsYou posted exactly same answer here and here. If you can give exactly same answer then you should mark question as duplicated, not duplicate answer too.
-
GabiM over 2 yearsThis doesn't work for me (Java 8?). Iterating
targetedStrategyClass.getMethods()
, the declaringClass for the overriding method is stillTargetedStrategyClass
, not the superclass. @Hardy commented the same on this question stackoverflow.com/a/4821768/2743585