Мне нужно определить, расширяет ли объект 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)
то же самое, но у вас должны быть экземпляры классов, а не сами классы
Liast<Class> getAllInterfaces(Class<?> clazz){
List<Class> interfaces = new ArrayList<>();
Collections.addAll(interfaces,clazz.getInterfaces());
if (!clazz.getSuperclass().equals(Object.class)){
interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));
}
return interfaces ;
}
Вам следует добавить контекст, объясняющий ваш ответ, а не просто код.
Мне кажется, что все усложняется, чем есть на самом деле; повторная реализация того, что уже предоставляет Java. Предполагая, что весь код здесь правильный, он просто даст тот же ответ, что и однострочный isAssignableFrom из других ответов.