[英]InstantiationException when constructing an object that implements the List interface
[英]identify the list of interface a object implements
有没有办法识别对象实现的接口列表。 例如:LinkedList实现List和Queue接口。
是否有可用于确定它的Java语句?
听起来你正在寻找Class.getInterfaces()
:
public static void showInterfaces(Object obj) {
for (Class<?> iface : obj.getClass().getInterfaces()) {
System.out.println(iface.getName());
}
}
例如,在打印的LinkedList
的实现上:
java.util.List
java.util.Deque
java.lang.Cloneable
java.io.Serializable
请注意, java.util.Queue
不会显示,因为java.util.Deque
扩展了它 - 所以如果你想要实现所有的接口,你需要递归。 例如,使用以下代码:
public static void showInterfaces(Object obj) {
showInterfaces(obj.getClass());
}
public static void showInterfaces(Class<?> clazz) {
for (Class<?> iface : clazz.getInterfaces()) {
System.out.println(iface.getName());
showInterfaces(iface);
}
}
...输出是:
java.util.List
java.util.Collection
java.lang.Iterable
java.util.Deque
java.util.Queue
java.util.Collection
java.lang.Iterable
java.lang.Cloneable
java.io.Serializable
...现在你会注意到Iterable
和Collection
会发生两次:)你可以在一个集合中收集“到目前为止看到的接口”,以避免重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.