答案在于getClasses
javadoc中突出显示的位
返回一个数组,其中包含表示所有公共类和接口的 Class 对象,这些公共类和接口是此 Class 对象表示的类的成员。这包括从超类继承的公共类和接口成员以及类声明的公共类和接口成员。
据我所知,getClasses()
返回它从超类继承的类以及其超类的静态类。接口不是超类,因此根据 javadoc,我们不应该期望在接口上声明的任何静态类都会被返回。
出下面的继承测试,才testInheritanceClasses
通过。
1)类扩展超类看到Enclosed
:
public static class RootClass {
public static class Enclosed {}
}
public static class LeafClass extends RootClass {}
@Test
public void testInheritanceClasses() {
Class<?> enclosing = LeafClass.class;
Class<?>[] enclosed = enclosing.getClasses();
System.out.println(Arrays.deepToString(enclosed));
Assert.assertNotEquals(0, enclosed.length);
}
2)接口“扩展”一个接口看不到Enclosed
public interface Root {
class Enclosed {}
}
public interface Leaf extends Root {}
@Test
public void testInheritanceInterfaces() {
Class<?> enclosing = Leaf.class;
Class<?>[] enclosed = enclosing.getClasses();
System.out.println(Arrays.deepToString(enclosed));
Assert.assertNotEquals(0, enclosed.length);
}
3)实现接口的类看不到Enclosed
:
public interface Root {
class Enclosed {}
}
public static class LeafImplementingRoot implements Root {}
@Test
public void testInheritanceImplements() {
Class<?> enclosing = LeafImplementingRoot.class;
Class<?>[] enclosed = enclosing.getClasses();
System.out.println(Arrays.deepToString(enclosed));
Assert.assertNotEquals(0, enclosed.length);
}