Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method showing up in getDeclaredMethods(), but can't be found with getDeclaredMethod(), why?

I am trying to use the snippet:

GenericModel.class.getDeclaredMethod("findById");

to get a Method called "findById". I know the method exists, because when I call:

GenericModel.class.getDeclaredMethods();

the method is listed in the array returned.

However, when using the first snippet, I am getting a java.lang.NoSuchMethodException? Why?

like image 334
josef.van.niekerk Avatar asked Jan 20 '23 03:01

josef.van.niekerk


2 Answers

Presumably findById actually takes parameters. But you are searching for a method by that name that takes none. Most likely what you want is:

GenericModel.class.getDeclaredMethod("findById", new Class[] { int.class });

This will match a method that has a signature like this:

Object findById(int id) { ... }
like image 55
Kirk Woll Avatar answered Jan 21 '23 18:01

Kirk Woll


getDeclaredMethod() receives parameter types as well, and you didn't give it any, and in the case of findViewById, it's a method that receives an int as parameter.

like image 39
MByD Avatar answered Jan 21 '23 17:01

MByD