Java examples for Reflection:Interface
Returns all interfaces implemented by the specified class including all interfaces implemented by super classes.
//package com.java2s; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { public static void main(String[] argv) throws Exception { Class clazz = String.class; System.out.println(java.util.Arrays .toString(getImplementedInterfaces(clazz))); }/*w w w . j a v a 2s.com*/ /** * Returns all interfaces implemented by the specified class * including all interfaces implemented by super classes. * If the specified class is itself an interfaces or the * specified class does not implement any interfaces, this * method returns an empty array. * @param clazz the Class * @return all interfaces implemented by the specified class */ public static Class[] getImplementedInterfaces(Class clazz) { if (clazz.isInterface()) return new Class[0]; Class[] classes = getInheritanceHierarchy(clazz); Set interfaceSet = new HashSet(); for (int ii = 0; ii < classes.length; ii++) { interfaceSet.addAll(Arrays.asList(classes[ii].getInterfaces())); } return (Class[]) interfaceSet .toArray(new Class[interfaceSet.size()]); } /** * Returns the inheritance hierarchy of the specified class. * The returned array includes all superclasses of the specified class * starting with the most general superclass, which is * <code>java.lang.Object</code>. The returned array also * includes the class itself as the last element. Implemented * interfaces are not included. * @param clazz the Class * @return all superclasses, most general superclass first */ public static Class[] getInheritanceHierarchy(Class clazz) { List classes = new ArrayList(); Class currentClass = clazz; while (null != currentClass) { classes.add(currentClass); currentClass = currentClass.getSuperclass(); } Collections.reverse(classes); return (Class[]) classes.toArray(new Class[classes.size()]); } }