繁体   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