In this shot, we will learn how to determine if a given object is an annotation in Java.
Class
class in JavaJava 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.
isAnnotation()
methodThe 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.
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());}}
Arrays
class.SuppressWarnings
annotation, using the .class
property. Then, we assign it to the suppressWarningsClass
variable.suppressWarningsClass
is an annotation, using the isAnnotation()
method.Arrays
class, using the .class
property. Then, we assign it to the arraysClass
variable.arraysClass
is an annotation, using the isAnnotation()
method.