In Java, an interface is a set of functionalities that an object of a given class is expected to implement. A class is said to implement an interface when it contains all the methods defined in the interface. An interface can extend another interface, thus there are hierarchies of interfaces similarly to class hierarchies. Differently from the single inheritance model characterizing relationships between classes, a class can implement more than one interface, and an interface can extend more than one interface.

The java.lang.Class class provides a method to retrieve the interfaces implemented in a given class. This method is called getInterfaces() and returns an array (possibly with zero length) of Class objects representing the different interfaces implemented by a given class. It is worth noting that Class objects can refer not only to Java classes, but also to interfaces. If a Class object represents an interface, calling getInterfaces() on it returns an array with all the interfaces extended by this interface.

The example code below illustrates how to use the getInterfaces() method. The interfaces implemented by the java.util.List class are retrieved and stored in an array, then the contents of this array are printed on the standard output.

public class GetInterfaces {
  public static void main(String str[]){
    Class listClass = java.util.List.class;
    Class[] interfaces = listClass.getInterfaces();
    for (int i =0; i < interfaces.length; i++) {
      System.out.println(intfs[i]);
    }
  }
}

Note that the Class object representing java.util.List is obtained without instantiating any List object: instead, the special static field class (defined implicitly in any class) is used to obtain a reference to the Class object. When a Class object representing an interface is passed to the println() method, its toString() method is implicitly called, which, in case of interfaces, returns the string “interface” followed by the fully qualified name of the interface. The output of the above program indicates that the List class implements one interface, i.e. java.util.Collection.

 

interface java.util.Collection