如何获取类实现的所有接口?

时间:2013-11-21 21:39:37

标签: java reflection

在我的测试中,为什么Aa.class.getClasses()返回[]而不是[A.class]?毕竟Apublic

import org.junit.Test;  
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GetClassesTest{     

    public interface A {}
    class Aa implements A {}

    @Test
    public void getClassesShouldWork(){
        assertThat( "should fail, but passes", Aa.class.getClasses(), is( new Class[]{} ) );
//      assertThat( "should pass, but fails!", Aa.class.getClasses(), is( new Class[]{ A.class } ) );
    }
}

1 个答案:

答案 0 :(得分:-1)

这是因为getClasses()返回类定义而非实现的类和接口。你想要的是Class.getInterfaces()

import org.junit.Test;  
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GetInterfacesTest{     

    public interface A {}
    class Aa implements A {}

    @Test
    public void getInterfacesDoesWork(){
        assertThat( "should pass, and passes", Aa.class.getInterfaces(), is( new Class[]{A.class} ) );
    }
}