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

你应该使用isAssignableFrom

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

你可以使用下面的函数来获得所有实现的接口

Class[] intfs = clazz.getInterfaces();

你可以使用class.getInterfaces() ,然后检查接口类是否在那里。

Class someInterface; // the interface you want to check for 
Class x; // 
Class[] interfaces = x.getInterfaces();

for (Class i : interfaces) {
    if (i.toString().equals(someInterface.toString()) {
        // if this is true, the class implements the interface you're looking for
    }
}
链接地址: http://www.djcxy.com/p/57406.html

上一篇: 获取应用了类型参数的已实现接口的Type实例

下一篇: 确定一个类是否在Java中实现一个接口