确定一个类的扩展接口

时间:2020-03-06 14:33:20  来源:igfitidea点击:

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

package a.b.c.d;
    public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{
    }

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

If this Class represents either the
  Object class, an interface, a
  primitive type, or void, then null is
  returned.

因此,以下操作将无效。

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
}

有任何想法吗?

解决方案

使用Class.getInterfaces,例如:

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

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

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();
}

编辑:添加了一些代码来获取特定类的所有超类和接口。

看看Class.getInterfaces();

List<Object> list = new ArrayList<Object>();
for (Class c : list.getClass().getInterfaces()) {
    System.out.println(c.getName());
}

Class.isAssignableFrom()是否可以满足需求?

Class baseInterface = Class.forName("a.b.c.d.IMyInterface");
Class extendedInterface = Class.forName("a.b.d.c.ISomeOtherInterface");

if ( baseInterface.isAssignableFrom(extendedInterface) )
{
  // do stuff
}

if (interface.isAssignableFrom(extendedInterface))

是你想要的

我总是总是一开始就倒退顺序,但是最近意识到这与使用instanceof完全相反

if (extendedInterfaceA instanceof interfaceB)

是同一件事,但是我们必须具有类的实例,而不是类本身