我知道这样的事实,Class#getDeclaredMethods返回类的声明方法,Class#getMethods另外还包含继承的方法.简而言之:
getDeclaredMethods is subset of getMethods
Run Code Online (Sandbox Code Playgroud)
但是下面的输出如何合理呢?
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());
}
Run Code Online (Sandbox Code Playgroud)
它打印:
access$1 synthetic(true)
compare synthetic(false)
compare synthetic(true)
Run Code Online (Sandbox Code Playgroud)
对于以下内容:
for (Method m : claz.getMethods()) {
System.out.println(m.getName() + " synthetic(" + m.isSynthetic()+")" );
}
Run Code Online (Sandbox Code Playgroud)
它打印:
compare synthetic(false)
compare synthetic(true)
...//removed others for brievity
Run Code Online (Sandbox Code Playgroud)
当我们尝试打印方法时A.class,除了可见方法之外,它还包含2个额外的合成方法compare(Object, Object)(桥接方法)和access$1(用于Bar访问外部类的元素Foo).
两者都打印出来declaredMethods.但为什么不getMethods打印access$1?