如何在Java运行时检查方法是否存在? [英] How To Check If A Method Exists At Runtime In Java?

查看:296
本文介绍了如何在Java运行时检查方法是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would one go about checking to see if a method exists for a class in Java? Would a try {...} catch {...} statement be good practice?

推荐答案

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

您可以尝试以下方法:

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

这将不起作用,因为该方法将在编译时解决.

This will not work, since the method will be resolved at compile-time.

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

You really need to use reflection for it. And if you have access to the source code of the method you want to call, it's even better to create an interface with the method you want to call.

[更新]附加信息是:有一个接口可能存在两个版本,一个是旧版本(无通缉方法),一个是新版本(有通缉方法).基于此,我提出以下建议:

[Update] The additional information is: There is an interface that may exist in two versions, an old one (without the wanted method) and a new one (with the wanted method). Based on that, I suggest the following:

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,因此实际对象是否具有该方法都没有关系.

This code tests whether the method getAllowedNether exists in the interface, so it doesn't matter whether the actual objects have the method or not.

如果必须经常调用方法getAllowedNether,并且因此而导致性能问题,我将不得不考虑一个更高级的答案.此刻现在应该没问题.

If the method getAllowedNether must be called very often and you run into performance problems because of that, I will have to think of a more advanced answer. This one should be fine for now.

这篇关于如何在Java运行时检查方法是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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