确定类是否在Java中实现接口 [英] Determine if a Class implements a interface in Java

查看:166
本文介绍了确定类是否在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆