Is there a way to identify the list of interfaces a object implements. For example: LinkedList implements both List and Queue interfaces.
Is there any Java statement that I can use to determine it?
It sounds like you're looking for Class.getInterfaces()
:
public static void showInterfaces(Object obj) {
for (Class<?> iface : obj.getClass().getInterfaces()) {
System.out.println(iface.getName());
}
}
For example, on an implementation of LinkedList
that prints:
java.util.List
java.util.Deque
java.lang.Cloneable
java.io.Serializable
Note that java.util.Queue
isn't displayed by this, because java.util.Deque
extends it - so if you want all the interfaces implemented, you'd need to recurse. For example, with code like this:
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);
}
}
... the output is:
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
... and now you'll note that Iterable
and Collection
occur twice :) You could collect the "interfaces seen so far" in a set, to avoid duplication.
See more on this question at Stackoverflow