Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a Class implements a interface in Java

I have a Class object. I want to determine if the type that the Class object represents implements a specific interface. I was wondering how this could be achieved?

I have the following code. Basically what it does is gets an array of all the classes in a specified package. I then want to go through the array and add the Class objects that implement an interface to my map. Problem is the isInstance() takes an object as a parameter. I can't instantiate an interface. So I am kind of at a loss with this. Any ideas?

Class[] classes = ClassUtils.getClasses(handlersPackage); for(Class clazz : classes) {     if(clazz.isInstance(/*Some object*/)) //Need something in this if statement     {         retVal.put(clazz.getSimpleName(), clazz);     } } 
like image 471
user489041 Avatar asked Aug 27 '12 15:08

user489041


People also ask

How do you know if a class implements an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. 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.

Which keyword validates whether a class implements an interface?

With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.

Does a class implement an interface?

A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types.


1 Answers

You should use isAssignableFrom:

if (YourInterface.class.isAssignableFrom(clazz)) {     ... } 
like image 176
Flavio Avatar answered Oct 02 '22 13:10

Flavio