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

标签 java methods try-catch exists

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

最佳答案

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

你可以试试这个:

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

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

您确实需要为此使用反射。而且,如果您可以访问要调用的方法的源代码,则最好为要调用的方法创建一个接口(interface)。

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

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;
      }
    }));
  }
}

此代码测试接口(interface)中是否存在方法getAllowedNether,因此实际对象是否具有该方法并不重要。

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

关于java - 如何在 Java 运行时检查方法是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058621/

相关文章:

java - 在 Java 中使用 lambda 作为类的方法

swift - 在 If/Else 中捕获 Nil 错误

java - 哪个更快?在更多 runnables 中做更少的工作,还是在更少的 runnables 中做更多的工作? (执行服务)

java - 如何杀死另一个类中的一个类的实例?

java - 非 void 方法中缺少 return 语句编译

java - 是否可以将 count(*) 和 groupBy 添加到 Spring Data Jpa 规范?

java - 将任何枚举传递给方法

methods - 向 Julia 基运算符添加新方法

javascript - 使用 nodejs + express 处理服务器端和客户端错误的最佳方法是什么

c# - 抛出异常时 try catch 性能问题