2014-02-07 18 views
0

我認爲我誤解了Java反射的一些相當深層次的東西。我記錄了我的方法是什麼(包括它應該作爲參數採用什麼),以及我傳入的內容,並且它們完美匹配。 getMethod()明確地檢索正確的方法,但是當我調用它時,它給了我NoSuchMethodException錯誤。Java反射API:getMethod()正常工作,調用失敗

我針對此調用createsession。

protected void onHandleIntent(Intent i){ 
    String methodName = i.getStringExtra("methodName"); 
    String[] data = i.getStringArrayExtra("data"); 

    Method m = null; 
    try{ 
     MyClass c = new MyClass(); 
     m = c.getClass().getMethod(methodName, String[].class); 
     Log.v("this works", "This is printed, no problem"); 
     m.invoke(c, data); 
     Log.v("this does not", "will not be printed"); 
    } catch(Exception NoSuchMethodException){ 
     Log.v("nosuchmethod", methodName + " was not found"); 
    } 
} 

public void createsession(String[] data) 
    { 
     System.out.println(data[0]); 
    } 

這是我所得到的,當我打印出我的方法對象用的ToString()後,它已經通過getMethod分配:

method﹕ public void com.myPackage.myApp.MyClass.createsession(java.lang.String[]) 

這讓我覺得,getMethod不問題區域,因爲這是所有返回正確的信息......

編輯 這是工作的全部時間...

問題是,try塊現在變成了它或者我調用的任何函數產生的所有異常。在這種程度上,當被調用的函數本身返回一個異常時,invoke方法將其解釋爲它真正知道的唯一失敗:「NoSuchMethodException」。我看到NoSuchMethodExceptions只是一個NullPointerException在被調用的方法進入錯誤的catch塊。

我想我會留下這個問題,並永遠不回答,作爲公平的警告花費。我覺得這對其他人來說可能是有用的知識。

+0

你的目標方法是不是私人的?確保你的方法是公開的! – MengMeng

+0

對不起,我應該澄清一下:createsession _is_的目標方法。 – Caerulius

+0

哦,我看到它確實是公開的... Ops〜我不知道〜一切似乎都沒事 – MengMeng

回答

0

無需創建新實例。 試試這個

m = MyClass.class.getMethod(methodName, String[].class); 
    Log.v("this works", "This is printed, no problem"); 
    m.invoke(this, data); 
    Log.v("this does not", "will not be printed"); 
+0

這並沒有解決我的問題。我認爲這可能是獲取方法名稱,最佳實踐和所有方法的更好方法。然而,我仍然在同一條船上。 – Caerulius

+0

我剛纔修改它。嘗試 – MengMeng

+0

恐怕仍然沒有...方法找到正確,但總是在調用時拋出異常。 – Caerulius

相關問題