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?
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?
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.
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 superclassesc.getSuperclass()
returns the immediate superclass of the given classObject
, you get all methodsObject
, then let the condition be while (c != null)