Java - 带反射的NoSuchMethodException

时间:2013-04-11 08:54:01

标签: java reflection

执行时我得到NoSuchMethodException

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

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

但是类RegasificacionDTO确实有一个名为setPrioridad(int i)的公共方法,如果调试我调用:

operacionDTO.getClass().getMethods()

然后我得到一个Method数组,其中有一个setPrioridad。我尝试了一些其他类似的方法,我得到了同样的错误。

3 个答案:

答案 0 :(得分:11)

您需要包含参数签名。

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

答案 1 :(得分:4)

方法getMethod()接受方法名称和参数类型的varargs数组。在您的情况下,您应该致电getMethod("setPrioridad", int.class),一切都会有效。

这是因为在java中(与大多数面向对象语言一样),您可以定义具有相同名称和不同签名的多个方法,因此系统使用给定的参数类型区分它们。

答案 2 :(得分:1)

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