I'd like to be able to write, for example
Method[] getMethods(Class<?> c)
which would do the same thing as the existing
Class.getMethods()
but also include private and protected methods. Any ideas how I could do this?
public Method[] getMethods(Class<?> c) {
List<Method> methods = new ArrayList<Method>();
while (c != Object.class) {
methods.addAll(Arrays.asList(c.getDeclaredMethods()));
c = c.getSuperclass();
}
return methods.toArray(new Method[methods.size()]);
}
To explain:
getDeclaredMethods
returns all methods that are declared by a certain class, but not its superclasses
c.getSuperclass()
returns the immediate superclass of the given classObject
, you get all methodsObject
, then let the condition be while (c != null)
Use Class.getDeclaredMethods()
instead. Note that unlike getMethods()
, this won't return inherited methods - so if you want everything, you'll need to recurse up the type hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With