Class.getClasses()不使用接口的继承类

时间:2013-09-09 14:06:47

标签: java reflection

有人可以解释为什么test()通过而testInheritance()没有?

public class IPanDeviceEnclosedClassesTest {

    public static interface Root {
       class Enclosed {}
    }

    public static interface Leaf extends Root {}

    @Test
    public void testInheritance() {
        Class<?> enclosing  = Leaf.class;
        Class<?>[] enclosed = enclosing.getClasses();
        assertNotEquals(0, enclosed.length);
    }

    @Test
    public void test() {
        Class<?> enclosing  = Root.class;
        Class<?>[] enclosed = enclosing.getClasses(); // getDeclaredClasses() works as well
        assertNotEquals(0, enclosed.length);
    }
}

1 个答案:

答案 0 :(得分:2)

答案取决于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);
}