2015-03-03 39 views
0

我想調用使用反射的方法。使用反射在Java中調用方法並獲取返回值

的方法是:

public String format(String text,int value) 
{ 
    return text+" "+value; 
} 

所以,它有2個參數:一個字符串和一個int。並且它返回一個String。 我該怎麼稱呼它?

+0

井的名字,有多遠你走到這一步?你有沒有設法找到使用反射的方法?你嘗試過調用它嗎?發生了什麼? – 2015-03-03 13:04:50

+0

我試圖做一些事情,但我有一個問題,繼續 公共字符串格式(字符串文本,int值){ return text +「」+ value; } – 2015-03-03 13:04:54

+2

那麼把你到目前爲止的問題放到你的問題中,並告訴我們你卡在哪裏。閱讀http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html或類似的教程,如果你一開始就陷入困境。 – 2015-03-03 13:06:55

回答

1
try { 
     Class<?> type = Foo.class; 
     Method method = type.getMethod("format", String.class, int.class); 
     //as the method is not static, you need to have an instance of the class to be able to invoke the method 
     Foo instance = new Foo(); 
     String string = (String) method.invoke(instance, "string", 42); 
    } catch (Exception toBeHandled) {} 

並更換Foo與你的類

+0

@ aaron-digulla,不需要你需要一個類的實例來調用一個方法,因爲它不是靜態的。這就是爲什麼我創建了類 – WeMakeSoftware 2015-03-06 09:08:05

+0

的實例當然,你是對的。需要更多的咖啡;-) – 2015-03-06 09:18:48