简体   繁体   English

奇怪的行为-Class#getDeclaredMethods vs getMethods

[英]Weird behavior - Class#getDeclaredMethods vs getMethods

I am aware of the fact that, Class#getDeclaredMethods returns declared methods of the class and Class#getMethods in additional contains the inherited methods. 我知道以下事实: Class#getDeclaredMethods返回该类的声明方法,而Class#getMethods另外还包含继承的方法。 In short: 简而言之:

getDeclaredMethods is subset of getMethods

But how is the below output justified? 但是下面的输出如何合理?

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());
}

It prints: 它打印:

access$1 synthetic(true)
compare synthetic(false)
compare synthetic(true)

For the below: 对于以下内容:

for (Method m : claz.getMethods()) {
    System.out.println(m.getName() + " synthetic(" + m.isSynthetic()+")" );
}

It prints: 它打印:

compare synthetic(false)
compare synthetic(true)
...//removed others for brievity

When we try printing methods of A.class , apart from visible methods it contains 2 additional synthetic methods compare(Object, Object) (bridge method) and access$1 (for Bar to access elements of outer class Foo ). 当我们尝试A.class打印方法时,除可见方法外,它还包含2个其他合成方法compare(Object, Object) (bridge方法)和access$1 (用于Bar访问外部类Foo元素)。

Both get printed in declaredMethods . 两者都在declaredMethods打印。 But why doesn't getMethods print access$1 ? 但是为什么getMethods不打印access$1呢?

access$1 is not public - you can verify it by printing Modifier.isPublic(m.getModifiers()) . access$1不是公开的-您可以通过打印Modifier.isPublic(m.getModifiers())

getMethods() only shows public methods : getMethods() 仅显示公共方法

Returns an array containing Method objects reflecting all the public member methods of the class [...] 返回一个包含Method对象的数组,该对象反映类[...]的所有公共成员方法

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

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