如何快速确定是否在Java中重写了方法 [英] How to quickly determine if a method is overridden in Java

查看:210
本文介绍了如何快速确定是否在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天全站免登陆