2015-01-08 72 views
0

如果已知參數和參數類型的數量,我可以使用變量名稱調用具有參數的方法,但如何獲取聲明的方法if if if arguments和參數類型僅在搜索[搜索方法]時才知道。如果參數類型未知,則通過變量調用參數

public static void invokeMethod (String myClass, 
           String myMethod, 
           Class[] params, Object[] args) 
          throws Exception { 
    Class c = Class.forName(myClass); 
    Method m = c.getDeclaredMethod(myMethod, params); 
    Object i = c.newInstance(); 
    Object r = m.invoke(i, args); 

}

invokeMethod("myLib", "sampleMethod", new Class[] {String.class, String.class}, 
     new Object[] 
     {new String("Hello"), new String("World")}); 

如果我不知道計數和Class[]類型的?如何動態管理這個?我將通過命令行或套接字獲取參數和方法。所以我不知道哪種方法會收到。

編輯 - 我試過下面東西 -

Class[] css = new Class[10] ; 
Object[] obj = new Object[10]; 
       int argLn = params.length; 
      if (argLn > 1) { 

       func = params[0].trim(); 
       for (int Idx = 1; Idx < argLn; ++Idx) { 

        arg.add(params[Idx]); 
        try { 
         Integer.parseInt((params[Idx])); 
         css[Idx-1] = String.class; 
        } catch (NumberFormatException ne) { 
         css[Idx-1] = int.class; 

        } 
       } 

但exception- NoSuchMethodException結束了。

+1

您是否知道如何動態創建和填充數組(無需將其寫入源代碼中)? – immibis

+0

我編輯了這個問題。 – Rilwan

+0

現在你已經發布了一些代碼,我認爲這個堆棧溢出指南適用於:「尋求調試幫助的問題(」爲什麼不是這個代碼工作?「)必須包括所需的行爲,*特定的問題或錯誤*和*在問題本身中重現它所需的最短代碼。「你在那裏的代碼片段並不能很好地展示你在做什麼。 – immibis

回答

0

這是在Oracle教程網站上討論的 - 請參閱"Obtaining Method Type Information"部分 - 關於反思的一般教程。

總之 - 你打電話後

Method m = c.getDeclaredMethod(myMethod, params); 

你需要的東西是這樣的:

Class<?>[] pType = m.getParameterTypes(); 

和/或(取決於你的方法是否會在他們的參數類型使用泛型)

Type[] gpType = m.getGenericParameterTypes(); 

返回數組的長度會給你參數的個數,成員thei r類或類型。您可以直接將pType陣列傳遞給您的invokeMethod()方法