如何快速确定一个方法是否在 Java 中被覆盖 [英] How to quickly determine if a method is overridden in Java

查看:42
本文介绍了如何快速确定一个方法是否在 Java 中被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我可以确定同一类中的另一个方法没有被覆盖,我可以对我的一个方法应用一种可能的优化.这只是一个轻微的优化,所以反射是不可能的.我是否应该创建一个受保护的方法来返回所讨论的方法是否被覆盖,以便子类可以使其返回 true?

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?

推荐答案

我不会这样做.它违反了封装并改变了您的类应该做的事情的契约,而实现者并不知道.

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

这篇关于如何快速确定一个方法是否在 Java 中被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆