Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

identify the list of interface a object implements

Tags:

java

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?

like image 301
user1050619 Avatar asked Oct 09 '13 15:10

user1050619


People also ask

What are List interface implementations?

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.

How do you check if an object implements an interface?

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.

What is the interface of an object?

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".

What is interface implement?

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 ).


1 Answers

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.

like image 84
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet