我不会的 它违反了封装,并且在实现者不知道的情况下更改了类应该执行的约定。
但是,如果必须这样做,最好的方法是调用
class.getMethod("myMethod").getDeclaringClass();如果返回的类是您自己的,则不会被覆盖;如果还有其他内容,则该子类已覆盖它。是的,这只是反思,但仍然很便宜。
不过,我确实喜欢您的保护方法。看起来像这样:
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. }}


