简体   繁体   English

Java 反射:getMethods() 和 getDeclaredMethods() 之间的区别

[英]Java Reflection: Difference between getMethods() and getDeclaredMethods()

有人可以详细说明一下,并解释这两种方法之间的区别,以及何时/为什么要使用其中一种方法而不是其他方法

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 ). getDeclaredMethods包括由类本身声明所有方法,而getMethods只返回公共方法,但也包括从基类(这里是java.lang.Object )继承的方法。

Read more about it in the Javadocs for getDeclaredMethod and getMethods .getDeclaredMethodgetMethods的 Javadocs 中阅读有关它的更多信息。

Short Version精简版

Method方法 Public上市 Non-public非公开 Inherited遗传
getMethods() ✔️ ✔️ ✔️ ✔️
getDeclaredMethods() ✔️ ✔️ ✔️ ✔️

Long version长版

Methods方法 getMethods()获取方法() getDeclaredMethods 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM