2011-08-14 165 views
11

如何檢查Java中的類是否存在方法? try {...} catch {...}聲明是否是一種好的做法?如何檢查Java中運行時是否存在方法?

+0

你使用反射嗎?否則,我不確定你在問什麼... – Neil

+0

try/catch與方法存在有什麼關係?除非你指的是'Iterator'接口,'remove'的實現允許拋出'UnsupportedOperationException'嗎? –

+1

你在談論什麼樣的檢查現有方法?反射? – Jaka

回答

21

我假設你要檢查的方法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必須經常調用,並且因此遇到性能問題,我將不得不考慮更高級的答案。這一個應該現在罰款。

+0

該方法不在我的代碼,但在一個鏈接的jar - 這將工作嗎? – jrtc27

+0

你能說出它是哪種方法嗎?該方法是來自'interface',所以你可以簡單地用'instanceof'運算符來查詢它的存在嗎? –

+0

編譯器會經過您指定的jar並找到所有的方法,如果它找不到,它會報錯並提示錯誤信息 – Jaka

2

我會用一個單獨的方法來處理異常,並有一個空檢查,檢查方法存在

例:如果(空= 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; 
} 
相關問題