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



