确定一个类是否在 Java 中实现了一个接口 [英] Determine if a Class implements a interface in 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)) {
...
}
这篇关于确定一个类是否在 Java 中实现了一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!