[英]Detecting whether a method/function exists in Java
在Java中是否有一個方法/函數來檢查另一個方法/函數是否可用,就像PHP中的function_exists(functionName)
一樣?
這里我指的是靜態類的方法/函數。
您可以使用反射了解Java中是否存在方法。
獲取您感興趣的類的Class
對象,並使用方法名稱和參數類型調用getMethod()
。
如果該方法不存在,則會拋出NoSuchMethodException
。
另請注意,“函數”在Java中稱為方法。
最后但同樣重要的是:請記住, 如果您認為自己需要這個 ,那么您可能會遇到設計問題。 反射(這是調用實際Java類的方法被調用)是Java的一個相當專業的特性,通常不應該在業務代碼中使用(雖然它被大量使用並且在一些公共庫中有一些很好的效果)。
我懷疑你正在尋找Class.getDeclaredMethods
和Class.getMethods
,它們將為你提供類的方法。 然后,您可以測試您要查找的那個是否存在,以及它的參數是什么等。
您可以使用Reflection查找方法是否存在:
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Class clazz = Test.class;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals("fooBar")) {
System.out.println("Method fooBar exists.");
}
}
if (clazz.getDeclaredMethod("fooBar", null) != null) {
System.out.println("Method fooBar exists.");
}
}
private static void fooBar() {
}
}
但是反射並不是很快,所以在使用它時要小心(可能會緩存它)。
嘗試使用Class class =)的Class.getMethod()
方法
public class Foo {
public static String foo(Integer x) {
// ...
}
public static void main(String args[]) throws Exception {
Method fooMethod = Foo.class.getMethod("foo", Integer.class);
System.out.println(fooMethod);
}
}
我的解決方案使用反射...
public static boolean methodExists(Class clazz, String methodName) {
boolean result = false;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(methodName)) {
result = true;
break;
}
}
return result;
}
您可以使用反射API來實現此目的。
YourStaticClass.getClass().getMethods();
你可以這樣做
Obj.getClass().getDeclaredMethod(MethodName, parameterTypes)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.