如何在 Java 运行时检查方法是否存在?

新手上路,请多包涵

如何检查 Java 中的类是否存在方法? try {...} catch {...} 声明是好的做法吗?

原文由 jrtc27 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 455
2 个回答

我假设您想检查方法 doSomething(String, Object)

你可以试试这个:

 boolean methodExists = false;
try {
  obj.doSomething("", null);
  methodExists = true;
} catch (NoSuchMethodError e) {
  // ignore
}

这是行不通的,因为该方法将在编译时解析。

你真的需要为它使用反射。而且,如果您可以访问要调用的方法的源代码,则最好使用要调用的方法创建一个接口。

[更新] 附加信息是:有一个接口可能存在两个版本,一个旧版本(没有想要的方法)和一个新版本(有想要的方法)。基于此,我提出以下建议:

 package so7058621;

import java.lang.reflect.Method;

public class NetherHelper {

  private static final Method getAllowedNether;
  static {
    Method m = null;
    try {
      m = World.class.getMethod("getAllowedNether");
    } catch (Exception e) {
      // doesn't matter
    }
    getAllowedNether = m;
  }

  /* Call this method instead from your code. */
  public static boolean getAllowedNether(World world) {
    if (getAllowedNether != null) {
      try {
        return ((Boolean) getAllowedNether.invoke(world)).booleanValue();
      } catch (Exception e) {
        // doesn't matter
      }
    }
    return false;
  }

  interface World {
    //boolean getAllowedNether();
  }

  public static void main(String[] args) {
    System.out.println(getAllowedNether(new World() {
      public boolean getAllowedNether() {
        return true;
      }
    }));
  }
}

这段代码测试接口中是否存在方法 getAllowedNether ,所以实际对象是否有该方法并不重要。

如果必须经常调用方法 getAllowedNether 并且因此遇到性能问题,我将不得不考虑更高级的答案。这个现在应该没问题。

原文由 Roland Illig 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题