Can someone please elaborate on this, and explain the difference between the two methods, and when/why you would want to use one over the others
getDeclaredMethods includes all methods declared by the class itself, whereas getMethods returns only public methods, but also those inherited from a base class (here from java.lang.Object).
Read more about it in the Javadocs for getDeclaredMethod and getMethods.
| Method | Public | Non-public | Inherited |
|---|---|---|---|
getMethods() |
✔️ | ❌ | ✔️ |
getDeclaredMethods() |
✔️ | ✔️ | ❌ |
| Methods | getMethods() | getDeclaredMethods |
|---|---|---|
| public | ✔️ | ✔️ |
| protected | ❌ | ✔️ |
| private | ❌ | ✔️ |
| static public | ✔️ | ✔️ |
| static protected | ❌ | ✔️ |
| static private | ❌ | ✔️ |
| default public | ✔️ | ✔️ |
| default protected | ❌ | ✔️ |
| default private | ❌ | ✔️ |
| inherited public | ✔️ | ❌ |
| inherited protected | ❌ | ❌ |
| inherited private | ❌ | ❌ |
| inherited static private | ✔️ | ❌ |
| inherited static protected | ❌ | ❌ |
| inherited static private | ❌ | ❌ |
| default inherited public | ✔️ | ❌ |
| default inherited protected | ❌ | ❌ |
| default inherited private | ❌ | ❌ |
If your goal, like mine, was to get public methods of a class:
| Method | Public | Non-public | Inherited |
|---|---|---|---|
getMethods() |
✔️ | ❌ | ✔️ |
getDeclaredMethods() |
✔️ | ✔️ | ❌ |
| getPublicMethods() | ✔️ | ❌ | ❌ |
and nothing else:
| Methods | getPublicMethods() |
|---|---|
| public | ✔️ |
| protected | ❌ |
| private | ❌ |
| static public | ❌ |
| static protected | ❌ |
| static private | ❌ |
| default public | ❌ |
| default protected | ❌ |
| default private | ❌ |
| inherited public | ❌ |
| inherited protected | ❌ |
| inherited private | ❌ |
| inherited static private | ❌ |
| inherited static protected | ❌ |
| inherited static private | ❌ |
| default inherited public | ❌ |
| default inherited protected | ❌ |
| default inherited private | ❌ |
You have to do it yourself:
Iterable<Method> getPublicMethods(Object o) {
List<Method> publicMethods = new ArrayList<>();
// getDeclaredMethods only includes methods in the class (good)
// but also includes protected and private methods (bad)
for (Method method : o.getClass().getDeclaredMethods()) {
if (!Modifier.isPublic(method.getModifiers())) continue; //only **public** methods
if (!Modifier.isStatic(method.getModifiers())) continue; //only public **methods**
publicMethods.add(method);
}
return publicMethods;
}
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