1

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.

1
  • You need to specify the data types of your parameters in an array and pass it to getMethod(...) as well. Commented Aug 22, 2013 at 14:02

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.