2013-04-11 51 views
1

執行時,我得到一個NoSuchMethodException爪哇 - NoSuchMethodException與反思

operacionDTO.getClass().getMethod("setPrioridad").invoke(operacionDTO, 0); 

java.lang.NoSuchMethodException: xxxx.api.service.dto.RegasificacionDTO.setPrioridad() 

但類RegasificacionDTO確實有一個叫setPrioridad(int i)公共方法,如果在調試的時候我打電話:

operacionDTO.getClass().getMethods() 

然後我得到一組方法,其中有一個setPrioridad。我嘗試了一些其他類似的方法,我得到了同樣的錯誤。

回答

11

您需要包含參數簽名。

operacionDTO.getClass().getMethod("setPrioridad", Integer.TYPE) 
3

方法getMethod()接受方法名稱和參數類型的可變參數數組。在你的情況下,你應該打電話getMethod("setPrioridad", int.class),一切都會工作。

這是因爲在java中(如在大多數面向對象的語言中),您可以定義幾個具有相同名稱和不同簽名的方法,因此係統使用給定的參數類型區分它們。

1
operacionDTO.getClass().getMethod("setPrioridad",new Class[]{Integer.TYPE or Integer.class}).invoke(operacionDTO, 0);