[英]Java - reflection getDeclaredMethods in declared order strange behaviour
[英]Java Reflection: Difference between getMethods() and getDeclaredMethods()
有人可以詳細說明一下,並解釋這兩種方法之間的區別,以及何時/為什么要使用其中一種方法而不是其他方法
getDeclaredMethods
包括由類本身聲明的所有方法,而getMethods
只返回公共方法,但也包括從基類(這里是java.lang.Object
)繼承的方法。
在getDeclaredMethod
和getMethods
的 Javadocs 中閱讀有關它的更多信息。
方法 | 上市 | 非公開 | 遺傳 |
---|---|---|---|
getMethods() |
✔️ | ❌ | ✔️ |
getDeclaredMethods() |
✔️ | ✔️ | ❌ |
方法 | 獲取方法() | getDeclaredMethods |
---|---|---|
上市 | ✔️ | ✔️ |
受保護 | ❌ | ✔️ |
私人的 | ❌ | ✔️ |
靜態公共 | ✔️ | ✔️ |
靜電保護 | ❌ | ✔️ |
靜態私有 | ❌ | ✔️ |
默認公開 | ✔️ | ✔️ |
默認保護 | ❌ | ✔️ |
默認私有 | ❌ | ✔️ |
繼承公眾 | ✔️ | ❌ |
繼承保護 | ❌ | ❌ |
繼承私有 | ❌ | ❌ |
繼承的靜態私有 | ✔️ | ❌ |
繼承的靜態保護 | ❌ | ❌ |
繼承的靜態私有 | ❌ | ❌ |
默認繼承公共 | ✔️ | ❌ |
默認繼承受保護 | ❌ | ❌ |
默認繼承私有 | ❌ | ❌ |
如果你的目標和我一樣,是獲取一個類的公共方法:
方法 | 上市 | 非公開 | 遺傳 |
---|---|---|---|
getMethods() |
✔️ | ❌ | ✔️ |
getDeclaredMethods() |
✔️ | ✔️ | ❌ |
獲取公共方法() | ✔️ | ❌ | ❌ |
僅此而已:
方法 | 獲取公共方法() |
---|---|
上市 | ✔️ |
受保護 | ❌ |
私人的 | ❌ |
靜態公共 | ❌ |
靜電保護 | ❌ |
靜態私有 | ❌ |
默認公開 | ❌ |
默認保護 | ❌ |
默認私有 | ❌ |
繼承公眾 | ❌ |
繼承保護 | ❌ |
繼承私有 | ❌ |
繼承的靜態私有 | ❌ |
繼承的靜態保護 | ❌ |
繼承的靜態私有 | ❌ |
默認繼承公共 | ❌ |
默認繼承受保護 | ❌ |
默認繼承私有 | ❌ |
你必須自己做:
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.