Reputation: 153
Is there any way to take a method using reflection without specifying its parameters?
I tried this:
method = className.class.getMethod("nameOfTheMethod");
Where nameOfTheMethod
is a function with 5 parameters.
But it thinks that nameOfTheMethod
is a function without parameters, and gives me java.lang.NoSuchMethodException
.
Upvotes: 1
Views: 181
Reputation: 2415
You need to specify the Parameter types
Try
Class[] cArg = new Class[5];
cArg[0] = Long.class;
cArg[1] = Long.class;
cArg[2] = Long.class;
cArg[3] = Long.class;
cArg[4] = Long.class;
Method lMethod = c.getMethod("nameOfMethod", cArg);
Replace the longs with whatever type your parameters are of respectively.
Upvotes: 0
Reputation: 4038
You can achieve this by using getDeclaredMethods()
and iterating the returned array.
Method[] methods = className.class.getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("nameOfTheMethod")) {
// found
break;
}
}
This way has the downside, that it only works reliable for not overloaded methods. However, you can easily take this further, so an array or set of all methods with the specified name is found.
Upvotes: 1
Reputation: 2610
You can't do it like that, the getMethod
needs the number of parameters.
What you could use is getMethods
or getDeclaredMethods
, depending what you're looking for, and match any of them with the name you want.
You could get more than 1 of them matching the name but with different parameters.
getMethods
will
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces
while getDeclaredMethods
will
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
Upvotes: 1
Reputation: 279960
You can get all methods
declared by the class or interface represented by this Class object.
with
Method[] methods = ClassName.class.getDeclaredMethods();
Iterate through them and find yours. This isn't safe if your method is overloaded as you will still have to check the parameters.
Upvotes: 2