簡體   English   中英

奇怪的行為-Class#getDeclaredMethods vs getMethods

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM