Getting SuperInterfaces in java

2019-06-16 17:02发布

I have been trying to do this for quite some time now and can't seem to get the desired output.

What I want to do is have a class name say java.util.Vector

get the:

  • the directly implemented interfaces if java.util.Vector.
  • the interfaces directly implemented by the superclasses.
  • and, transitively, all superinterfaces of these interfaces.

Any help would be appreciated.

3条回答
Viruses.
2楼-- · 2019-06-16 17:29

If you are open to use another library : use apache-commons-lang

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-16 17:38

You could do a BFS using the reflection for it.

Start with a Set<Class<?>> that contains only Vector, and iteratively increase the set with new elements using Class.getInterfaces() and Class.getSuperclass()

Add the just added elements to the Queue [which is needed for the BFS run]. Terminate when the queue is empty.

Post processing: iterate the Set - and take only objects that are interfaces using Class.isInterface()

Should look something like that:

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);
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-06-16 17:41

Although java.util.Vector is not an interface, and thus you cannot extend it with an interface, what you can do is use a library like Reflections to accommodate these sorts of features. Reflections allows you to scan the classpath and query for a set of conditions like what implements or extends the given class/interface. Ive used it successfully on a couple projects where I needed to scan for interface implementations and annotated classes.

Here's the explicit link: http://code.google.com/p/reflections/

Additionally, if you are looking to just find out what class/interface a class extends/implements you can just use the class reflection api via the class attribute.

Here's some examples:

//get all public methods of Vector
Vector.class.getMethods();
//get all methods of the superclass (AbstractList) of Vector
Vector.class.getSuperclass().getMethods();
//get all interfaces implemented by Vector
Vector.class.getInterfaces();
查看更多
登录 后发表回答