Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the interface name from the implementation class

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?

like image 783
Jatin Sehgal Avatar asked Jan 31 '13 11:01

Jatin Sehgal


People also ask

How do you access the interfaces implemented by a class?

The getClass(). getInterfaces() method return an array of Class that represents the interfaces implemented by an object.

Can we know which interfaces are implemented by a class?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

How do you identify a class interface?

Differences between a Class and an Interface:A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance.

How do I find the implementation class of an interface in eclipse?

Open Java Search, enter the interface name, click "Implementors" and you will "find which classes implement a particular interface."


2 Answers

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();
like image 183
PermGenError Avatar answered Oct 08 '22 06:10

PermGenError


Class  aClass = ... //obtain Class object. 
Class[] interfaces = aClass.getInterfaces();
like image 42
TheWhiteRabbit Avatar answered Oct 08 '22 06:10

TheWhiteRabbit