Java Annotation
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
Let’s make things easy… In Simple terms, Java annotations are special note or tag we apply to our Java code which provide extra information and doesn’t affect functionality.
Annotation were introduced into Java in Java SE 5 and belongs to java.lang.annotation package.
Types of Annotations:
Below are some of the important types of annotation we maily use on the daily basis.
- Marker Annotations → Its a blank interface does not include any variables or methods.
@interface MyAnnotation {
}
@MyAnnotation
Class HelloWorld {
}- Single value Annotations → This annotation contains Single method.
@interface MyAnnotation {
int value() default 0;
}
@MyAnnotation(value=6)
Class HelloWorld {
}- Multi value annotations → This annotation contains multiple variables and methods.
@interface MyAnnotation {
int value() default 0;
String text() default "Hello";
}
@MyAnnotation(value=6, text="hi")
Class HelloWorld {
}Annotation Categorization:
- Predefined Annotations → These are default inbuilt annotations provided by Java. e.g. @Override, @Deprecated, @SuppressWarnings, etc. It instruct compiler about specific behaviour.
@Override annotation force subclass to override parent class methods with the same method name, return type, and parameter list.
@Deprecated annotation is a marker annotation which signifies the particular class, method, variable, etc. got deprecated and has been replaced by a newer one.
@SuppressWarnings annotation helps us to suppress code warnings.
public class Student {
@Override
public String toString() {
return "Student toString() method.";
}
@Deprecated
public String oldMethod() {
return "Student oldMethod() method.";
}
@SuppressWarnings("deprecated")
public String testMethod() {
return "Student oldMethod() method.";
}
}@SafeVarargs @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.
2. Meta Annotations → Annotations that apply to other annotations. Meta-Annotations are used to provide information about how the annotation itself should be used.
Common Meta-Annotations in Java
@Retention
@Target
@Documented
@Inherited
Get Imran Khan’s stories in your inbox
Join Medium for free to get updates from this writer.
@Retention → This specifies how long annotations with the annotated type are to be retained.
Common retention policies include:
- RetentionPolicy.SOURCE: Discarded by the compiler.
- RetentionPolicy.CLASS: Retained in the class file but not available at runtime.
- RetentionPolicy.RUNTIME: Retained at runtime, so they can be read reflectively.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}@Target → Specifies the kinds of program element to which the annotation type is applicable.
Common targets include:
- ElementType.TYPE: Class, interface (including annotation type), or enum declaration.
- ElementType.FIELD: Field (including enum constants).
- ElementType.METHOD: Method declaration.
- ElementType.PARAMETER: Formal parameter declaration.
- ElementType.CONSTRUCTOR: Constructor declaration.
- ElementType.LOCAL_VARIABLE: Local variable declaration.
- ElementType.ANNOTATION_TYPE: Annotation type declaration.
- ElementType.PACKAGE: Package declaration.
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value();
}@Documented → It annotates to documented by javadoc by default.
import java.lang.annotation.Documented;
@Documented
public @interface MyAnnotation {
String value();
}@Inherited → This annotation indicates that an annotation type is automatically inherited and will be inherited by subclasses of that class.
import java.lang.annotation.Repeatable;
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
String value();
}
public @interface MyAnnotations {
MyAnnotation[] value();
}3. Custom Annotations → Follow below syntax to create custom annotation:
SYNTAX:
// Provide annotation name and declare methods with default value.
@interface <Annotation_Name> {
<Data_Type> <Method_Name>() default <value>;
}
// SAmple Annotation Class
@interface MyAnnotation {
int value() default 0;
String text() default "Hello";
}Below is an end to end example for Annotation:
package com.javadoubts.core.schedulers;
import java.lang.annotation.*;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@interface MyCustomAnnotation {
String text() default "One";
int number() default 0;
}
@MyCustomAnnotation(text = "Two", number = 10)
class MyClass {
// Consume custom annotation
@MyCustomAnnotation(text = "Three", number = 5)
public void myMethod() {}
}
public class MyAnnotation {
public static void main(String[] args) {
// Below source code is to access method level annotation.
Method[] methods = MyClass.class.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyCustomAnnotation.class)) {
MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);
System.out.println("Method Text: " + annotation.text());
System.out.println("Method Number: " + annotation.number());
}
}
// Below source code is to access class level annotation.
MyClass myClass = new MyClass();
MyCustomAnnotation annotation = myClass.getClass().getAnnotation(MyCustomAnnotation.class);
System.out.println("Class Text: " +annotation.text());
System.out.println("Class Number: " + annotation.number());
}
}OUTPUT:
Method Text: Three
Method Number: 5
Class Text: Two
Class Number: 10
Annotation Usage
- Instructions → Give instructions to the compiler in one or the other way to detect errors or suppress warnings. e.g. @Override, @Deprecated, @SuppressWarnings, etc.
- 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 → To give instructions to the program at runtime. These annotations are accessed using Java Reflection such as custom annotation we created above.
Annotation Advantages:
- Enhanced code readability
- Reduce boilerplate code
- Simplified Code
- Framework and Tool Integration ease
I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.
You can follow me for upcoming blogs follow.
Thank you!










