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