Unveiling the Power of Annotations in Java (Part 1)

Shubhranshu Gupta
4 min readJun 19, 2024

Java annotations are a powerful feature that allows developers to add metadata to their code. This metadata can then be used by the compiler or at runtime to influence the program's behavior. In this blog, we’ll dive into what annotations are, how they work, and how you can create and use them effectively in your Java projects.

What Are Annotations?

Annotations are a form of metadata that provide data about a program but are not part of the program itself. They are used to give information to the compiler or to be processed at runtime by tools and frameworks. Annotations are preceded by the @ symbol can be applied to classes, methods, variables, parameters, and other elements.

Why Were Annotations Introduced in Java?

Annotations were introduced in Java as part of JDK 5 to address several needs in modern software development. They provide a way to add metadata to Java code, which can be used by the compiler, development tools, and frameworks to perform various tasks. Here are the primary reasons annotations were introduced in Java:

  1. Simplify Code and Reduce Boilerplate
  2. Enable Compiler Checks
  3. Enhance Development Tools
  4. Facilitate Framework Development
  5. Improve Readability and Maintainability
  6. Enable Custom Annotations

Type of Annotations

Java annotations can be broadly categorized into three types:

  1. Built-in Annotations: These are provided by the Java language and are used to give the compiler special instructions.
  2. Meta-Annotations: These are used to define other annotations. They are annotations applied to other annotations.
  3. Custom Annotations: These are defined by developers to meet specific needs in their applications.
Types of Annotation

General Purpose Built in Annotation

Let’s explore some of the commonly used built-in annotations in Java:

1. @Override

This annotation indicates that a method is intended to override a method in a superclass. It helps to avoid errors by ensuring that the method overrides an existing method in the parent class.

@Override
public String toString() {
return "MyClass";
}

2. @Deprecated

This annotation marks a method, class, or field as deprecated, meaning it should no longer be used. The compiler issues a warning when deprecated elements are used.

@Deprecated
public void oldMethod() {
System.out.println("old method");
}

3. @SuppressWarnings

This annotation tells the compiler to suppress specific warnings that it would otherwise generate. It is often used to suppress unchecked warnings in generics.

@SuppressWarnings("unchecked")
public void myMethod() {
List myList = new ArrayList();
}

4. @SafeVarargs

This annotation is used to suppress warnings about heap pollution that can occur when using varargs (variable-length argument lists) with generics. This annotation can be applied to methods and constructors that use varargs, ensuring the compiler that the method or constructor does not perform any unsafe operations on the varargs parameters. @SafeVarargs annotation can only be applied to:

  • Static methods
  • Final instance methods
  • Constructors
@SafeVarargs
public static <T> void safeVarargsMethod(T... args) {
for (T arg : args) {
System.out.println(arg);
}
}

Meta Annotation

Meta-annotations are annotations that are applied to other annotations to provide information about how the annotations should be used. The main meta-annotations in Java are:

1. @Retention

Specifies how long the annotation is retained. The possible values are:

  • RetentionPolicy.SOURCE: Annotations are discarded by the compiler.
  • RetentionPolicy.CLASS: Annotations are recorded in the class file but not retained at runtime.
  • RetentionPolicy.RUNTIME: Annotations are retained at runtime and can be accessed via reflection.
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// ...
}

2. @Target

Indicates the kinds of program elements to which an annotation type is applicable. The possible values are:

  • ElementType.TYPE: Class, interface (including annotation type), or enum declaration.
  • ElementType.FIELD: Field declaration (including enum constants).
  • ElementType.METHOD: Method declaration.
  • ElementType.PARAMETER: Parameter declaration.
  • ElementType.CONSTRUCTOR: Constructor declaration.
  • ElementType.LOCAL_VARIABLE: Local variable declaration.
  • ElementType.ANNOTATION_TYPE: Annotation type declaration.
  • ElementType.PACKAGE: Package declaration.
@Target(ElementType.METHOD)
public @interface MyAnnotation {
// ...
}

3. @Inherited

Indicates that an annotation type is automatically inherited. If a class is annotated with an inherited annotation type, then all its subclasses will also be annotated with that annotation.

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
// ...
}

4. @Documented

Indicates that an annotation type should be documented by Javadoc and similar tools. By default, annotations are not included in Javadoc.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
// ...
}

5. @Repeatable

This meta-annotation allows the same annotation to be applied multiple times to a single element. Before Java 8, if you wanted to apply an annotation more than once, you would need to use a containing annotation. With @Repeatable, this is no longer necessary.

import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)
public @interface Schedule {
String day();
}

public @interface Schedules {
Schedule[] value();
}

@Schedule(day = "Monday")
@Schedule(day = "Wednesday")
@Schedule(day = "Friday")
public void meeting() {
// ...
}

Conclusion

Annotations in Java are a versatile tool that provides metadata to the Java compiler and runtime environment. They help to enforce certain rules, facilitate code generation, and enable framework features. Understanding the different types of annotations and how to create custom annotations can significantly enhance your ability to write clean, maintainable, and efficient Java code.

In the next part of our blog series, we will dive into how to create custom annotations.

Stay tuned!

Reference:

https://www.baeldung.com/java-default-annotations

--

--