使用 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();
}
编辑:添加了一些代码来获取某个类的所有超类和接口。