奇怪的行为 - Class#getDeclaredMethods vs getMethods

时间:2014-05-24 11:33:24

标签: java reflection

我知道,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)(桥接方法)和access$1(用于Bar来访问元素外类Foo)。

两者都打印在declaredMethods。但为什么不getMethods打印access$1

1 个答案:

答案 0 :(得分:4)

access$1不公开 - 您可以通过打印Modifier.isPublic(m.getModifiers())来验证它。

getMethods() only shows public methods

  

返回一个包含Method对象的数组,这些对象反映了类[...]的所有 public 成员方法