List the Interfaces That a Class Implements in Java


The interfaces that are implemented by a class that is represented by an object can be determined using the java.lang.Class.getInterfaces() method. This method returns an array of all the interfaces that are implemented by the class.

A program that demonstrates this is given as follows −

Example

 Live Demo

package Test;
import java.lang.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      listInterfaces(String.class);
   }
   public static void listInterfaces(Class c) {
      System.out.println("The Class is: " + c.getName());
      Class[] interfaces = c.getInterfaces();
      System.out.println("The Interfaces are: " + Arrays.asList(interfaces));
   }
}

Output

The Class is: java.lang.String
The Interfaces are: [interface java.io.Serializable, interface java.lang.Comparable, interface java.lang.CharSequence]

Now let us understand the above program.

The method listInterfaces() is called with String.class in the method main(). A code snippet which demonstrates this is as follows −

listInterfaces(String.class);

In the method listInterfaces(), the method getName() is used to print the name of the class. Then the method getInterfaces() is used to return an array of all the interfaces that are implemented by the class. Then this array is printed using  Arrays.asList(). A code snippet which demonstrates this is as follows −

System.out.println("The Class is: " + c.getName());
Class[] interfaces = c.getInterfaces();
System.out.println("The Interfaces are: " + Arrays.asList(interfaces));

Updated on: 25-Jun-2020

503 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements