Java – Determine if a Class implements a interface in Java

javareflection

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);
    }
}

Best Answer

You should use isAssignableFrom:

if (YourInterface.class.isAssignableFrom(clazz)) {
    ...
}