I want to get all methods of a class, including public, protected, package and private methods, and including inherited methods.
Remember:
Class.getDeclaredMethods()gets public, protected, package and private methods, but excludes inherited methods.Class.getMethodsgets inherited methods, but only the public ones.
Before Java 8 we could do something along the lines of:
Collection<Method> found = new ArrayList<Method>();
while (clazz != null) {
for (Method m1 : clazz.getDeclaredMethods()) {
boolean overridden = false;
for (Method m2 : found) {
if (m2.getName().equals(m1.getName())
&& Arrays.deepEquals(m1.getParameterTypes(), m2
.getParameterTypes())) {
overridden = true;
break;
}
}
if (!overridden) found.add(m1);
}
clazz = clazz.getSuperclass();
}
return found;
But now, if the class implements some interface with default methods which are not overridden by concrete superclasses, these methods will escape the above detection. Besides, there are now rules concerning default methods with the same name, and these rules must be taken into account as well.
Question: What is the current recommended way of getting all methods of a class?
Aucun commentaire:
Enregistrer un commentaire