2012-01-26 42 views
0

我寫了一個程序,它必須要求要使用的方法(我使用java.lang.StringBuffer.append),那麼它必須說明它最多需要多少個參數,在這種情況下,我認爲這是3。用戶可以輸入儘可能多的參數,因爲他想要所有的字符串,然後程序會追加它們並將字符串打印出來。但有一些錯誤,我只是沒有發現錯誤。Java反射,獲取方法追加並使用它

import java.lang.reflect.*; 

import tio.*; 
public class MethodExecutor { 
    public static void main(String [] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException 
    { 
     String input = ""; 
     String input1 = ""; 
     String input2 = ""; 
     String argumenten[]; 
     int aantal = 0; 
     System.out.println("What method to invoke?"); 
     input = Console.in.readLine(); 

     input1 = input.substring(0,input.lastIndexOf(".")); 
     input2 = input.substring(input.lastIndexOf(".")+1,input.length()); 
     System.out.println(input2); 

     Class<?> c = Class.forName(input1); 
     Method m = c.getMethod(input2, null); 
     Class<?>[] parameterTypes = m.getParameterTypes(); 

     System.out.println("Needs max " + parameterTypes.length + " parameters."); 
     System.out.println("How many will you provide?"); 
     aantal = Console.in.readInt(); 
     argumenten = new String[aantal]; 
     for(int i = 0; i < argumenten.length; i++) 
      argumenten[i] = Console.in.readLine(); 

     System.out.println("Success"); 

     } 
} 

Tio只是一個獲取控制檯輸入的庫。

有人可以幫忙嗎?

親切的問候,

+0

什麼是錯,什麼是行爲,你期待什麼? – pgras

+0

我無法顯示.append所需的最大需求參數。所以我也不能用用戶給出的參數來執行函數。我認爲.getmethod不會給我正確的功能 – user1007522

回答

2

我認爲這...

Method m = c.getMethod(input2, null); 

...是要尋找與存儲在輸入2名,其中不帶參數的方法。

相反,我認爲你需要搜索每一個方法的類,然後打印出的那些的長度相匹配的名字

(從getMethod的Javadoc :)

返回一個Method該對象反映了由此Class對象表示的類或接口的指定公共成員方法。 name參數是一個字符串,用於指定所需方法的簡單名稱。 parameterTypes參數是一個Class對象的數組,以聲明的順序標識方法的形式參數類型。 如果parameterTypes爲null,則將其視爲空數組。

+0

因此,我需要使用getdeclaredmethods搜索所有內容,然後使用if測試,測試是否存在稱爲append的方法? – user1007522