Using .getDeclaredMethod to get a method from a class extending another

后端 未结 1 1428
悲哀的现实
悲哀的现实 2020-12-14 17:33

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

But that plugin c

相关标签:
1条回答
  • 2020-12-14 18:08

    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();
    }
    
    0 讨论(0)
提交回复
热议问题