[英]Weird behavior - Class#getDeclaredMethods vs getMethods
我知道以下事實: Class#getDeclaredMethods
返回該類的聲明方法,而Class#getMethods
另外還包含繼承的方法。 簡而言之:
getDeclaredMethods is subset of getMethods
但是下面的輸出如何合理?
class A implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return -1;
}
private Object baz = "Hello";
private class Bar {
private Bar() {
System.out.println(baz);
}
}
Bar b = new Bar();
}
for (Method m : claz.getDeclaredMethods()) {
System.out.println(m.getName()+ " " + m.isSynthetic());
}
它打印:
access$1 synthetic(true)
compare synthetic(false)
compare synthetic(true)
對於以下內容:
for (Method m : claz.getMethods()) {
System.out.println(m.getName() + " synthetic(" + m.isSynthetic()+")" );
}
它打印:
compare synthetic(false)
compare synthetic(true)
...//removed others for brievity
當我們嘗試A.class
打印方法時,除可見方法外,它還包含2個其他合成方法compare(Object, Object)
(bridge方法)和access$1
(用於Bar
訪問外部類Foo
元素)。
兩者都在declaredMethods
打印。 但是為什么getMethods
不打印access$1
呢?
access$1
不是公開的-您可以通過打印Modifier.isPublic(m.getModifiers())
。
getMethods()
僅顯示公共方法 :
返回一個包含Method對象的數組,該對象反映類[...]的所有公共成員方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.