Reputation: 2086
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
Upvotes: 80
Views: 36957
Reputation: 256671
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;
}
Upvotes: 25
Reputation: 262494
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
.
Upvotes: 110