Java - NoSuchMethodException with reflection

2019-08-05 10:53发布

问题:

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.

回答1:

You need to include the parameter signature.

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


回答2:

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.



回答3:

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