get All Interfaces As Set - Java Reflection

Java examples for Reflection:Interface

Description

get All Interfaces As Set

Demo Code


import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

public class Main{
    public static Set<Class<?>> getAllInterfacesAsSet(Class<?> clazz,
            ClassLoader classLoader) {
        if (clazz == null)
            return null;
        if (clazz.isInterface() && isVisible(clazz, classLoader)) {
            Set<Class<?>> set = CollectionUtil.createHashSet(1);
            set.add(clazz);/*  w  w  w  . j a  v  a2  s . c  om*/
            return set;
        }
        Set<Class<?>> interfaces = CollectionUtil.createLinkedHashSet();
        while (clazz != null) {
            Class<?>[] ifcs = clazz.getInterfaces();
            for (Class<?> ifc : ifcs) {
                interfaces.addAll(getAllInterfacesAsSet(ifc, classLoader));
            }
            clazz = clazz.getSuperclass();
        }
        return interfaces;
    }
    public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
        if (classLoader == null) {
            return true;
        }
        try {
            Class<?> actualClass = classLoader.loadClass(clazz.getName());
            return (clazz == actualClass);
            // Else: different interface class found...
        } catch (ClassNotFoundException ex) {
            // No interface class found...
            return false;
        }
    }
}

Related Tutorials