怎样获得一个工程中,实现了某一个接口的所有类?

terry_yip 2006-04-08 02:54:54
常常见到有一些接口本身是空的,没有定义任何方法,但是实现它的类,却可以被另一些类所识别,并对实现了这个接口的类进行某些操作,我想知道,用什么方法可以找到一个系统中所有现实了某一个接口的类,最好给出代码例子,谢谢。



...全文
183 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dan1980 2006-04-08
  • 打赏
  • 举报
回复
反射是可以得到接口的。Class的getInterfaces()方法。

import java.io.Serializable;

public class Test implements Serializable {

public static boolean hasImplemented(Object o, String interfaceName) {
Class[] interfaces = o.getClass().getInterfaces();
for(int i = 0; i < interfaces.length; i++)
if(interfaces[i].getName().equals(interfaceName)) return true;
return false;
}

public static void main(String[] args) {
String s = "hello, world";
Test f = new Test();
System.out.println(hasImplemented(s, "java.lang.Comparable")); //true
System.out.println(hasImplemented(f, "java.io.Serializable")); //true
}
}
terry_yip 2006-04-08
  • 打赏
  • 举报
回复
据我所知,反射只能找到一个类的父类,而不能找到接口。
yeyu710 2006-04-08
  • 打赏
  • 举报
回复
这好像是java的反射机制吧,具体也没搞过哦!

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧