确定类的扩展接口

shs*_*mer 11 java reflection interface

我需要确定表示接口的Class对象是否扩展了另一个接口,即:

 package a.b.c.d;
    public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{
    }
Run Code Online (Sandbox Code Playgroud)

根据规范, Class.getSuperClass()将为接口返回null.

如果此Class表示Object类,接口,基本类型或void,则返回null.

因此以下方法无效.

Class interface = Class.ForName("a.b.c.d.IMyInterface")
Class extendedInterface = interface.getSuperClass();
if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){
    //do whatever here
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

And*_*son 16

使用Class.getInterfaces,例如:

Class<?> c; // Your class
for(Class<?> i : c.getInterfaces()) {
     // test if i is your interface
}
Run Code Online (Sandbox Code Playgroud)

以下代码也可能有所帮助,它将为您提供一个包含某个类的所有超类和接口的集合:

public static Set<Class<?>> getInheritance(Class<?> in)
{
    LinkedHashSet<Class<?>> result = new LinkedHashSet<Class<?>>();

    result.add(in);
    getInheritance(in, result);

    return result;
}

/**
 * Get inheritance of type.
 * 
 * @param in
 * @param result
 */
private static void getInheritance(Class<?> in, Set<Class<?>> result)
{
    Class<?> superclass = getSuperclass(in);

    if(superclass != null)
    {
        result.add(superclass);
        getInheritance(superclass, result);
    }

    getInterfaceInheritance(in, result);
}

/**
 * Get interfaces that the type inherits from.
 * 
 * @param in
 * @param result
 */
private static void getInterfaceInheritance(Class<?> in, Set<Class<?>> result)
{
    for(Class<?> c : in.getInterfaces())
    {
        result.add(c);

        getInterfaceInheritance(c, result);
    }
}

/**
 * Get superclass of class.
 * 
 * @param in
 * @return
 */
private static Class<?> getSuperclass(Class<?> in)
{
    if(in == null)
    {
        return null;
    }

    if(in.isArray() && in != Object[].class)
    {
        Class<?> type = in.getComponentType();

        while(type.isArray())
        {
            type = type.getComponentType();
        }

        return type;
    }

    return in.getSuperclass();
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了一些代码来获取某个类的所有超类和接口.


Mat*_*att 10

if (interface.isAssignableFrom(extendedInterface))
Run Code Online (Sandbox Code Playgroud)

是你想要的

我总是首先得到倒序,但最近意识到它与使用instanceof完全相反

if (extendedInterfaceA instanceof interfaceB) 
Run Code Online (Sandbox Code Playgroud)

是同样的事情,但你必须有类的实例而不是类本身