suresh suresh - 3 months ago 6
Java Question

How to identify if class has implemented marker interface

I received this question during interview, the question is


How to identify if class has implemented marker interface


If there is a way to find, how to know which marker interface is implemented

Answer

Use Class#getInterfaces():

Determines the interfaces implemented by the class or interface represented by this object.

If this object represents a class, the return value is an array containing objects representing all interfaces implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this object. For example, given the declaration:

class Shimmer implements FloorWax, DessertTopping { ... }

suppose the value of s is an instance of Shimmer; the value of the expression:

s.getClass().getInterfaces()[0]

is the Class object that represents interface FloorWax; and the value of:

s.getClass().getInterfaces()[1]

is the Class object that represents interface DessertTopping.

Note however that this approach will not return true for the scenario where instead a superclass of Shimmer implements the interfaces, for example as below:

public interface FloorWax { }

public interface DesertTopping { }

public class Shimmer implements implements FloorWax, DessertTopping { }

public class ShimmerChild extends Shimmer {}

public static void main(String[] args) {
    // throws ArrayOutOfBoundsException
    System.out.println(new ShimmerChild().getClass().getInterfaces()[0]);
}

In a case where you would want for the below to return the interfaces, use the approach as described in @DylanMeeus answer with Class#isAssignableFrom()

Comments