如何确定Java类是否实现特定的接口 [英] How to determine if a Java Class implements a particular Interface

查看:191
本文介绍了如何确定Java类是否实现特定的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用反射来确定传入类是否实现了 IsWdidget 接口:

I'm trying to use reflection to determine whether a passed-in class implements an IsWdidget interface:

public boolean isAWidget(Class<?> clzz) {
    Class<?> runtimeClass = ClassLoader.getSystemClassLoader().loadClass(clzz.getName());
    Class<?>[] impls = runtimeClass.getInterfaces();
    for(Class<?> clz : impls)
        if(clz.getName().equals(IsWidget.class.getName()))
            return true;

    return false;
}

这是确定这个的最好/最有效的方法吗?我还看到 IsWidget.class.isAssignableFrom(Class<?>)方法...

Is this the best/most effecient way of determining this? I also see a IsWidget.class.isAssignableFrom(Class<?>) method...

推荐答案

我会使用 isAssignableFrom 方法来确定 IsWidget 是否为超级接口:

I would use the isAssignableFrom method to determine if IsWidget is a superinterface:

return IsWidget.class.isAssignableFrom(clzz);

从上面链接的Javadoc引用:

To quote from the linked Javadoc above:

确定由此Class对象
表示的类或接口是否与指定的
类或接口相同,或是其超类或超接口类参数。

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

这篇关于如何确定Java类是否实现特定的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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