确定类的扩展接口 [英] Determining the extended interfaces of a Class

查看:91
本文介绍了确定类的扩展接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to determine if a Class object representing an interface extends another interface, ie:

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

=http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getSuperclass() =noreferrer>规范 Class.getSuperClass( )将为接口返回null。

according to the spec Class.getSuperClass() will return null for an Interface.


如果此Class表示
Object类,接口,
基元类型或void,则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,例如: / p>

Use Class.getInterfaces such as:

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

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

Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class:

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。

Added some code to get all super-classes and interfaces of a certain class.

这篇关于确定类的扩展接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆