get All Interfaces As Array - Java Reflection

Java examples for Reflection:Interface

Description

get All Interfaces As Array

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 void main(String[] argv) throws Exception{
        Class clazz = String.class;
        System.out.println(java.util.Arrays.toString(getAllInterfacesAsArray(clazz)));
    }/*from  w  ww.  ja v a  2 s. co m*/
    public static Class<?>[] getAllInterfacesAsArray(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }

        List<Class<?>> interfacesFound = CollectionUtil.createArrayList();
        getAllInterfaces(clazz, interfacesFound);

        return interfacesFound.toArray(new Class<?>[0]);
    }
    public static List<Class<?>> getAllInterfaces(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }

        List<Class<?>> interfacesFound = CollectionUtil.createArrayList();
        getAllInterfaces(clazz, interfacesFound);

        return interfacesFound;
    }
    private static void getAllInterfaces(Class<?> clazz,
            List<Class<?>> interfacesFound) {
        while (clazz != null) {
            Class<?>[] interfaces = clazz.getInterfaces();

            for (int i = 0; i < interfaces.length; i++) {
                if (!interfacesFound.contains(interfaces[i])) {
                    interfacesFound.add(interfaces[i]);
                    getAllInterfaces(interfaces[i], interfacesFound);
                }
            }

            clazz = clazz.getSuperclass();
        }
    }
}

Related Tutorials