11

インターフェイスを表すClassオブジェクトが別のインターフェイスを拡張するかどうかを判断する必要があります。

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

仕様によると、 Class.getSuperClass()はインターフェイスに対してnullを返します。

このクラスが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
}

何か案は?

4

5 に答える 5

16

次のような 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();
}

編集:特定のクラスのすべてのスーパークラスとインターフェースを取得するためのコードを追加しました。

于 2008-09-22T18:27:49.033 に答える
10
if (interface.isAssignableFrom(extendedInterface))

あなたが欲しいものです

私は常に最初は順序を逆にしますが、最近、instanceof を使用するのとは正反対であることに気付きました

if (extendedInterfaceA instanceof interfaceB) 

同じことですが、クラス自体ではなくクラスのインスタンスが必要です

于 2008-09-22T18:30:31.260 に答える
2

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
}
于 2008-09-22T18:29:10.387 に答える
0

Class.getInterfaces(); を見てください。

List<Object> list = new ArrayList<Object>();
for (Class c : list.getClass().getInterfaces()) {
    System.out.println(c.getName());
}
于 2008-09-22T18:28:11.700 に答える