如何在 Java 中找到特定接口的所有(子)子接口?
How to find all (child) sub-interfaces of a particular interface in Java?
给定一个接口:
public interface A {};
具有继承接口:
public interface B extends A {}
public interface C extends A {}
如何以编程方式扫描以查找 B
和 C
? IE。如何做到这一点:
Type[] types = findAllSubInterfacesOfA(); // Returns [B.class, C.class]
注意:我试图在这里找到接口,不是 类或实例。
下面的代码片段应该可以做到。
public class FindSubinterfaces {
public static void main(String[] args) {
Class clazz = A.class;
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(Arrays.asList(ClasspathHelper.forClass(clazz))));
Set<Class<? extends List>> subTypes = reflections.getSubTypesOf(clazz);
for (Class c : subTypes) {
if (c.isInterface()) {
System.out.println("subType: " + c.getCanonicalName());
}
}
}
}
interface A {
};
interface B extends A {
}
interface C extends A {
}
class CA implements A {
}
abstract class DC implements C {
}
输出
subInterface: sub.optimal.reflections.B
subInterface: sub.optimal.reflections.C
给定一个接口:
public interface A {};
具有继承接口:
public interface B extends A {}
public interface C extends A {}
如何以编程方式扫描以查找 B
和 C
? IE。如何做到这一点:
Type[] types = findAllSubInterfacesOfA(); // Returns [B.class, C.class]
注意:我试图在这里找到接口,不是 类或实例。
下面的代码片段应该可以做到。
public class FindSubinterfaces {
public static void main(String[] args) {
Class clazz = A.class;
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(Arrays.asList(ClasspathHelper.forClass(clazz))));
Set<Class<? extends List>> subTypes = reflections.getSubTypesOf(clazz);
for (Class c : subTypes) {
if (c.isInterface()) {
System.out.println("subType: " + c.getCanonicalName());
}
}
}
}
interface A {
};
interface B extends A {
}
interface C extends A {
}
class CA implements A {
}
abstract class DC implements C {
}
输出
subInterface: sub.optimal.reflections.B
subInterface: sub.optimal.reflections.C