Java - NoSuchMethodException with reflection

2019-08-05 10:25发布

I get a NoSuchMethodException when executing:

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

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

But class RegasificacionDTO does have a public method called setPrioridad(int i), and if when debugging I call:

operacionDTO.getClass().getMethods()

Then I get an array of Method in which there is a setPrioridad. I've tried with some other similar methods and I get the same error.

3条回答
做自己的国王
2楼-- · 2019-08-05 11:05
 operacionDTO.getClass().getMethod("setPrioridad",new Class[]{Integer.TYPE or Integer.class}).invoke(operacionDTO, 0);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-05 11:06

You need to include the parameter signature.

 operacionDTO.getClass().getMethod("setPrioridad", Integer.TYPE)
查看更多
成全新的幸福
4楼-- · 2019-08-05 11:11

Method getMethod() accepts method name and an varargs array of parameter types. In your case you should call getMethod("setPrioridad", int.class) and everything will work.

This is because in java (as in most object oriented languages) you can define several methods with the same name and different signatures, so the system distinguishes among them using given parameter types.

查看更多
登录 后发表回答