java 判断函数是否存在_如何在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;

}

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

2020-10-09

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值