How to check if an object represents an interface in Java

Overview

This shot discusses how to determine if the object is an array in Java.

Class class in Java

Java has a class named Class in java.lang package. This class is used for reflection purpose.

Every object in Java belongs to a class. The metadata about the class is captured in the Class object. The metadata can be the class’s constructors, the class’s methods, the fields of the class, and so on.

Therefore, every object belongs to a class and has a Class object. The Class object of any given object can be obtained via the getClass() method.

isInterface() method

The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false, indicating that the given class is not an interface.

Syntax

public boolean interface();

Example

public class Main {
public static void main(String[] args) {
String stringObject = "educative";
System.out.printf("Is %s an interface - %s", stringObject, stringObject.getClass().isInterface());
System.out.println();
Class<?> interfaceClass = Iterable.class;
System.out.printf("Is %s an interface - %s", interfaceClass, interfaceClass.isInterface());
}
}

Explanation

  • Line 4: We define a string object stringObject.
  • Line 5: We use the isInterface() method to check if the stringObject belongs to an interface.
  • Line 8: We get the Class object for the Iterable interface, and store it in interfaceClass.
  • Line 9: We use the isInterface() method to check if the interfaceClass belongs to an interface.

Free Resources