栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我假设您要检查该方法

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;  }    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
必须经常调用该方法,并且因此而导致性能问题,我将不得不考虑一个更高级的答案。此刻现在应该没问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453253.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号