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();
Comments
-
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 over 11 yearsYou may also want to recurse on the interfaces extended by these interfaces.
-
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 over 11 yearsAnd if you want to get the Collection interface you have to call getInterface() on the interfaces returned by the first call.