How to check if a class object is an annotation in Java
Overview
In this shot, we will learn how to determine if a given object is an annotation in Java.
The Class class in Java
Java has a class by the name of Class in the java.lang package. This class is used for the purpose of reflection.
Every object in Java belongs to a class. The metadata about the class is captured in the Class object. This metadata can be the constructors, methods, or fields of the class, and so on.
Thus, 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.
The isAnnotation() method
The isAnnotation() method is used to check whether a class object is an annotation.
The syntax for this method is as follows:
public boolean isAnnotation()
The isAnnotation() method has no parameters and returns a boolean value. If the return value is true, then the class object is an annotation. If the return value is false, then the class object is not an annotation.
Code example
import java.util.Arrays;public class Main {public static void main(String[] args){Class<?> suppressWarningsClass = SuppressWarnings.class;System.out.printf("Is %s an annotation - %s", suppressWarningsClass, suppressWarningsClass.isAnnotation());System.out.println();Class<?> arraysClass = Arrays.class;System.out.printf("Is %s an annotation - %s", arraysClass, arraysClass.isAnnotation());}}
Code explanation
- Line 1: We import the
Arraysclass. - Line 6: We retrieve the class object of the
SuppressWarningsannotation, using the.classproperty. Then, we assign it to thesuppressWarningsClassvariable. - Line 7: We check if the
suppressWarningsClassis an annotation, using theisAnnotation()method. - Line 10: We retrieve the class object of the
Arraysclass, using the.classproperty. Then, we assign it to thearraysClassvariable. - Line 11: We check if the
arraysClassis an annotation, using theisAnnotation()method.