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

如何检查Java中是否存在类的方法? try {...} catch {...}声明是不是很好的做法?

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

你可以试试这个:

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

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

你真的需要使用reflection。 如果您可以访问要调用的方法的源代码,则最好使用要调用的方法创建接口。

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

 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方法并因此遇到性能问题,我将不得不考虑更高级的答案。 这个应该没问题。

使用Class.getMethod(...)函数时,Reflection API会抛出NoSuchMethodException

否则Oracle有一个很好的反思教程http://download.oracle.com/javase/tutorial/reflect/index.html

在java中,这称为reflection。 API允许您发现方法并在运行时调用它们。 这是一个指向文档的指针。 这是非常详细的语法,但它将完成工作:

http://java.sun.com/developer/technicalArticles/ALT/Reflection/

我将使用一个单独的方法来处理exception并进行空检查以检查方法是否存在

例如:if(null!= getDeclaredMethod(obj,“getId”,null))做你的东西……

 private Method getDeclaredMethod(Object obj, String name, Class... parameterTypes) { // TODO Auto-generated method stub try { return obj.getClass().getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }