确定类是否在Java中实现接口
我有一个 Class
对象。我想确定 Class
对象所代表的类型是否实现了特定的接口。我想知道如何实现这一目标?
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?
我有以下代码。基本上它的作用是获取指定包中所有类的数组。然后我想通过数组并将实现接口的Class对象添加到我的地图中。问题是 isInstance()
将对象作为参数。我无法实例化一个接口。所以我对此感到很茫然。有什么想法吗?
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
:
You should use isAssignableFrom
:
if (YourInterface.class.isAssignableFrom(clazz)) {
...
}