Annotations In Java
Java annotations are metadata (data about data) for our program source code. They provide additional information about the program to the compiler but are not part of the program itself. These annotations do not affect the execution of the compiled program.
Annotation formats
Annotations may also include elements (members/attributes/parameters).
Marker Annotations
Marker annotations do not contain members/elements. It is only used for marking a declaration.
Its syntax is:
@AnnotationName()
Since these annotations do not contain elements, parentheses can be excluded. For example,
@Override
Single element Annotations
A single element annotation contains only one element.
Its syntax is:
@AnnotationName(elementName = "elementValue")
If there is only one element, it is a convention to name that element as value.
@AnnotationName(value = "elementValue")
In this case, the element name can be excluded as well. The element name will be value by default.
@AnnotationName("elementValue")
Multiple element Annotations
These annotations contain multiple elements separated by commas.
Its syntax is:
@AnnotationName(element1 = "value1", element2 = "value2")
Types of Annotations
Target Constant | Annotations Can Be Applied To |
---|---|
ANNOTATION_TYPE | Another annotation |
CONSTRUCTOR | Constructor |
FIELD | Field |
LOCAL_VARIABLE | Local variable |
METHOD | Method |
PACKAGE | Package |
PARAMETER | Parameter |
TYPE | Class, Interface, or enumeration |
Use of Annotations
Compiler instructions - Annotations can be used for giving instructions to the compiler, detect errors or suppress warnings. The built-in annotations @Deprecated, @Override,@SuppressWarnings are used for these purposes.
Compile-time instructions - Compile-time instructions provided by these annotations help the software build tools to generate code, XML files and many more.
Runtime instructions - Some annotations can be defined to give instructions to the program at runtime. These annotations are accessed using Java Reflection.
Categories of Annotations
There are broadly 5 categories of annotations as listed:
Marker Annotations
Single value Annotations
Full Annotations
Type Annotations
Repeating Annotation
Let us discuss and we will be appending code where ever required if so.
Category 1: Marker Annotations
The only purpose is to mark a declaration. These annotations contain no members and do not consist of any data. Thus, its presence as an annotation is sufficient. Since the marker interface contains no members, simply determining whether it is present or absent is sufficient. @Override is an example of Marker Annotation.
Example
@TestAnnotation()
Category 2: Single value Annotations
These annotations contain only one member and allow a shorthand form of specifying the value of the member. We only need to specify the value for that member when the annotation is applied and don’t need to specify the name of the member. However, in order to use this shorthand, the name of the member must be a value.
Example
@TestAnnotation(“testing”);
Category 3: Full Annotations
These annotations consist of multiple data members, names, values, pairs.
Example
@TestAnnotation(owner=”Rahul”, value=”Class Coding”)
Category 4: Type Annotations
These annotations can be applied to any place where a type is being used. For example, we can annotate the return type of a method. These are declared annotated with @Target annotation.
Example
// Java Program to Demonstrate Type Annotation
// Importing required classes
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
// Using target annotation to annotate a type
@Target(ElementType.TYPE_USE)
// Declaring a simple type annotation
@interface TypeAnnoDemo{}
// Main class
public class GFG {
// Main driver method
public static void main(String[] args) {
// Annotating the type of a string
@TypeAnnoDemo String string = "I am annotated with a type annotation";
System.out.println(string);
abc();
}
// Annotating return type of a function
static @TypeAnnoDemo int abc() {
System.out.println("This function's return type is annotated");
return 0;
}
}
Output
I am annotated with a type annotation
This function's return type is annotated
Category 5: Repeating Annotations
These are the annotations that can be applied to a single item more than once. For an annotation to be repeatable it must be annotated with the @Repeatable annotation, which is defined in the java.lang.annotation package. Its value field specifies the container type for the repeatable annotation. The container is specified as an annotation whose value field is an array of the repeatable annotation type. Hence, to create a repeatable annotation, firstly the container annotation is created, and then the annotation type is specified as an argument to the @Repeatable annotation.
Example
// Java Program to Demonstrate a Repeatable Annotation
// Importing required classes
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
// Make Words annotation repeatable
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyRepeatedAnnos.class)
@interface Words
{
String word() default "Hello";
int value() default 0;
}
// Create container annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyRepeatedAnnos
{
Words[] value();
}
public class Main {
// Repeat Words on newMethod
@Words(word = "First", value = 1)
@Words(word = "Second", value = 2)
public static void newMethod()
{
Main obj = new Main();
try {
Class<?> c = obj.getClass();
// Obtain the annotation for newMethod
Method m = c.getMethod("newMethod");
// Display the repeated annotation
Annotation anno
= m.getAnnotation(MyRepeatedAnnos.class);
System.out.println(anno);
}
catch (NoSuchMethodException e) {
System.out.println(e);
}
}
public static void main(String[] args) { newMethod(); }
}
Output
@MyRepeatedAnnos(value={@Words(value=1, word="First"), @Words(value=2, word="Second")})
⌖
core
java
annotations
programming