Class getAnnotations() method in Java with Examples


The getAnnotations() method is a part of the java.lang.Class class in Java. It returns an array of Annotation objects representing all the annotations declared on the class. If there are no annotations present, it returns an empty array.

Syntax:

public Annotation[] getAnnotations()

Example 1:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value();
}

@MyAnnotation(value = "Hello World")
public class MyClass {
    public static void main(String[] args) {
        Annotation[] annotations = MyClass.class.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
    }
}

Output:

@MyAnnotation(value=Hello World)

In this example, we have defined a custom annotation @MyAnnotation with a single value value(). We have then annotated the MyClass with this annotation and used the getAnnotations() method to retrieve all the annotations declared on the class. We have then printed the annotations using a for-each loop.

Example 2:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value();
}

@MyAnnotation(value = "Hello World")
public class MyClass {
    public static void main(String[] args) {
        Annotation[] annotations = MyClass.class.getAnnotations();
        System.out.println("Number of annotations: " + annotations.length);
    }
}

Output:

Number of annotations: 1

In this example, we have used the getAnnotations() method to retrieve all the annotations declared on the MyClass. We have then printed the number of annotations using the length property of the array returned by the method.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.