27

So lets say I am trying to get a method from a class using Method m = plugin.getClass().getDeclaredMethod("getFile");.

But that plugin class is extending another class, which is the one with the getFile method. I am not quite sure if that would make it throw the NoSuchMethodException exception or not.

I know the class that the plugin is extending has the getFile method. Sorry if I sound confusing, a bit tired.

spongebob
  • 8,370
  • 15
  • 50
  • 83
PaulBGD
  • 2,018
  • 5
  • 22
  • 30

1 Answers1

76

It sounds like you just need to use getMethod instead of getDeclaredMethod. The whole point of getDeclaredMethod is that it only finds methods declared in the class you're calling it on:

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Whereas getMethod has:

C is searched for any matching methods. If no matching method is found, the algorithm of step 1 is invoked recursively on the superclass of C.

That will only find public methods though. If the method you're after isn't public, you should recurse up the class hierarchy yourself, using getDeclaredMethod or getDeclaredMethods on each class in the hierarchy:

Class<?> clazz = plugin.getClass();
while (clazz != null) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        // Test any other things about it beyond the name...
        if (method.getName().equals("getFile") && ...) {
            return method;
        }
    }
    clazz = clazz.getSuperclass();
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • If it helps, the reason I am using this is due to the method being private in the first place. Annd then you edit. Alright, I'll try the edit. – PaulBGD Jul 30 '13 at 17:42
  • @Ultimate: Well yes, that's pretty important. It would have helped if you'd mentioned that to start with. – Jon Skeet Jul 30 '13 at 17:43
  • Well, this was a while back. Sorry for not accepting this! – PaulBGD Sep 25 '14 at 21:03