Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to check if a class object is an annotation in Java

Ravi

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());
    }
}
The "isAnnotation()" method

Code explanation

  • Line 1: We import the Arrays class.
  • Line 6: We retrieve the class object of the SuppressWarnings annotation, using the .class property. Then, we assign it to the suppressWarningsClass variable.
  • Line 7: We check if the suppressWarningsClass is an annotation, using the isAnnotation() method.
  • Line 10: We retrieve the class object of the Arrays class, using the .class property. Then, we assign it to the arraysClass variable.
  • Line 11: We check if the arraysClass is an annotation, using the isAnnotation() method.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring