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?
The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.
Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.
An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".
The implements keyword is used to implement an interface . The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With