Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 227
programmingnewb Avatar asked Mar 27 '12 00:03

programmingnewb


1 Answers

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);
}
like image 130
amit Avatar answered Sep 22 '22 07:09

amit