在java中获取SuperInterfaces [英] Getting SuperInterfaces in java
问题描述
我一直试图这样做很长一段时间,似乎无法获得所需的输出。
I have been trying to do this for quite some time now and can't seem to get the desired output.
我想要的是有一个类名称 java.util.Vector
What I want to do is have a class name say java.util.Vector
得到:
- 直接实现的接口如果
java.util.Vector
。 - 由超类直接实现的接口。
- 以及传统上这些接口的所有超接口。
任何帮助都将不胜感激。
Any help would be appreciated.
推荐答案
<你可以使用 BFS .oracle.com / javase / tutorial / reflect /rel =nofollow>反射。
You could do a BFS using the reflection for it.
以开头设置< Class<?>>
仅包含 Vector
,并使用 Class.getInterfaces()
和 Class.getSuperclass ()
Start with a Set<Class<?>>
that contains only Vector
, and iteratively increase the set with new elements using Class.getInterfaces()
and Class.getSuperclass()
将刚刚添加的元素添加到队列
[这是BFS运行所需的]。当队列为空时终止。
Add the just added elements to the Queue
[which is needed for the BFS run]. Terminate when the queue is empty.
后处理:迭代 Set
- 并且只接受使用接口的对象 Class .isInterface()
Post processing: iterate the Set
- and take only objects that are interfaces using Class.isInterface()
看起来应该是这样的:
Class<?> cl = Vector.class;
Queue<Class<?>> queue = new LinkedList<Class<?>>();
Set<Class<?>> types =new HashSet<Class<?>>();
queue.add(cl);
types.add(cl);
//BFS:
while (queue.isEmpty() == false) {
Class<?> curr = queue.poll();
Class<?>[] supers = curr.getInterfaces();
for (Class<?> next : supers) {
if (next != null && types.contains(next) == false) {
types.add(next);
queue.add(next);
}
}
Class<?> next = curr.getSuperclass();
if (next != null && types.contains(next) == false) {
queue.add(next);
types.add(next);
}
}
//post processing:
for (Class<?> curr : types) {
if (curr.isInterface()) System.out.println(curr);
}
这篇关于在java中获取SuperInterfaces的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!