:::: MENU ::::

Saturday, May 25, 2024

Objectives

What is java Annotation?

How Java Annotation helps development?

What are the types of annotation?

How to declare a custom annotation?

What are the Java built in annotations?

What are the relations between Spring framework to annotation?

What is Java Annotation?

Java annotation is meta-data of classes, methods, and fields. It carries additional information. But It doesn’t change semetics meaning of program. With the help of annotation, programmer do aspect of programming at runtime. Not only runtime, Annotation retention policy would be source or class type and those have special meaning.

What are the types of Annotation?

Annotation can be categoried into two major. One is Annotation for declaration, another is Type annotation. Basically the name “declared” or “type” are come to mind. Because annotation can be apply in two situations. 1. When a class, method, or fields are being declared, annotation will be applied to carry additional information. 2. When a type is being mentioned, annotation can be applied at those place. E.g. Return type.

How to declare a custom annotation?

Annotation is basically an interface with extending Annotation interface from java.lang.annotation package. Syntax is pretty to understand. It is mantadory to put ‘@’ symbol in front of interface keyword. It can holds only methods.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
    public String str();
    public int val();
}

Let’s apply it on a class. MyAnno annotation is applied on “ReflectionClass”. Now the next important focus is how do we use this additional information? Pretty simple, below code snippets show the use of java Reflection API and how to get MyAnno’s information.

@MyAnno(str = "additional information", val = 10)
public class ReflectionClass {

    public static void main(String[] args) {
        ReflectionClass reflectionClass = new ReflectionClass();
        Class clazz = reflectionClass.getClass();
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.toString());
        }
    }
}

0 comments:

Post a Comment