Annotations in Java

The Annotations in Java are a form of the metadata that can be added to Java code to provide information about the code to compiler and runtime environment.

  • Built-in Annotations: These are the annotations provided by Java, such as, @Override, @Deprecated and @SuppressWarnings.
  • Custom Annotations: To Creating custom annotations to add metadata to our own code.
  • Annotation Processors: The Processing annotations at compile time to generate additional code or perform specific tasks.

Use Cases:

  • Code Organization: Adding information about code’s intended use, relationships or constraints.
  • Frameworks and Libraries: The Many Java frameworks use annotations for the configuration and behavior customization.
  • Documentation: The Generating documentation or providing hints to the tools and IDEs.

Example:

Java




//Java program to demonstrate Annotations 
import java.io.*;
import java.lang.annotation.*;
  
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
    String value() default "The Default Value";
}
public class AnnotationExample {
    @CustomAnnotation("The Custom Value")
    public void annotatedMethod() {
        // Method implementation
    }
}


Explanation of the Program:

  • The above Java program defines a custom annotation with the retention policy RUNTIME and Target Element type METHOD.
  • It then applies this annotation to the method in the AnnotationExample class.
  • When executed, the output is not explicitly visible in the code, but program demonstrates how to use annotations.
  • The Annotations themselves don’t produce output when the program runs.


Deep Dive into Java Reflection and Annotations

The Java Reflection and Annotations are powerful features that provide dynamic and metadata-driven capabilities to Java applications. The Reflection allows the examination and manipulation of the class properties, methods, and fields at runtime while Annotations provide a way to add metadata and behavior to the code.

Similar Reads

Reflection in Java

The Java Reflection is a mechanism that allows to inspect and interact with components of the Java class at runtime. It provides a way to examine or modify the runtime behavior of the applications....

Annotations in Java

...