Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection: Difference between getMethods() and getDeclaredMethods()

Tags:

java

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

like image 294
Rakib Avatar asked Apr 24 '17 09:04

Rakib


Video Answer


2 Answers

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.

like image 87
Thilo Avatar answered Oct 16 '22 09:10

Thilo


Short Version

Method Public Non-public Inherited
getMethods() ✔️ ✔️
getDeclaredMethods() ✔️ ✔️

Long version

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;
}
like image 6
Ian Boyd Avatar answered Oct 16 '22 11:10

Ian Boyd