Using Java Annotations

Using Annotations

Because an annotation itself is only a simple definition of a name and type, it is the caller’s responsibility to decide what processing should be performed according to the specified annotation. Annotation information can be obtained with the Method#getAnnotation method. Obtaining a Method object is the role of the Class#getMethod method. 1

AnnotationSample.java

package com.devkuma.basic.annotation;

import java.lang.reflect.Method;

public class AnnotationSample {
    @Version(1.0)
    public void annotationTest() {
        System.out.println("Released");
    }

    public static void main(String[] args) {
        try {
            // Get the annotationTest method.
            Method method = AnnotationSample.class.getMethod("annotationTest");
            // Get the Version annotation.
            Version version = method.getAnnotation(Version.class);
            // Execute if the Version annotation is 1.0 or higher.
            if (version.value() >= 1.0) {
                method.invoke(AnnotationSample.class.getDeclaredConstructor().newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Execution result:

Released

In this example, if the value of the retrieved Version annotation is 1.0 or higher, the method to which the annotation is applied, here annotationTest, is executed. To execute a method through a Method object, use the invoke method.


  1. This feature for accessing a class or its members is called reflection. ↩︎