Get the interface name from the implementation class

23,443

Solution 1

Using Reflection you can invoke the Class.getInterfaces() method which returns an Array of Interfaces that your class implements.

list.getClass().getInterfaces()[0];

To get just the name

list.getClass().getInterfaces()[0].getSimpleName();

Solution 2

Class  aClass = ... //obtain Class object. 
Class[] interfaces = aClass.getInterfaces();
Share:
23,443
Jatin Sehgal
Author by

Jatin Sehgal

A java developer

Updated on June 29, 2020

Comments

  • Jatin Sehgal
    Jatin Sehgal almost 4 years

    Example :

    List<String> list = new ArrayList<String>();
    //This would give me the class name for the list reference variable.
    list.getClass().getSimpleName();
    

    I want to get the Interface name from the list reference variable. Is there any way possible to do that?

  • Guillaume
    Guillaume over 11 years
    You may also want to recurse on the interfaces extended by these interfaces.
  • PermGenError
    PermGenError over 11 years
    @Guillaume good point, they would be class implementing order, for instance interface[0] would be java.util.List and interface[1] would be java.util.RandomAccess
  • Guillaume
    Guillaume over 11 years
    And if you want to get the Collection interface you have to call getInterface() on the interfaces returned by the first call.