Annotation

Annotations are a special kind of metadata that you can add to Java code elements such as classes, methods, fields, and parameters. They provide information about the code but do not directly affect program execution.

Important points about annotations:

  • Metadata Provider:
    Annotations describe information about the code, like instructions or configurations, which can be used by the compiler, tools, or runtime frameworks.
  • Non-Executable:
    They don’t change the logic or flow of the program by themselves but influence how tools or libraries process the code.
  • Compiler Assistance:
    Some annotations help the compiler detect errors or enforce coding standards. For example, @Override ensures a method properly overrides a superclass method.
  • Framework Integration:
    Popular Java frameworks such as Spring, JUnit, and Hibernate use annotations to reduce boilerplate code and configure behaviors declaratively.
  • Runtime Availability:
    Annotations can be retained at runtime (using @Retention(RetentionPolicy.RUNTIME)) and accessed via the Java Reflection API to dynamically adjust program behavior.

Common built-in annotations:

  • @Override — Ensures the method overrides a superclass method.
  • @Deprecated — Marks code as outdated, warning developers not to use it.
  • @SuppressWarnings — Tells the compiler to ignore specific warnings.
  • @FunctionalInterface — Marks an interface as a functional interface (with a single abstract method).

Creating custom annotations:

  • Use the @interface keyword.
  • Define elements (methods) that can be assigned values.
  • Control annotation retention and targets using meta-annotations like @Retention and @Target.

Meta-annotations control how annotations behave:

  • @Retention — Specifies how long annotations are retained (source, class file, or runtime).
  • @Target — Specifies where annotations can be applied (e.g., methods, fields, classes).
  • @Documented — Includes annotations in Javadoc.
  • @Inherited — Allows annotations to be inherited by subclasses.

Accessing annotations at runtime:

  • You can inspect annotations using Java Reflection.
  • This enables frameworks and libraries to modify or act upon code behavior dynamically.

Annotations make Java declarative, readable, and framework-friendly. They serve as metadata tags that can:

  • Assist compilers with validations.
  • Allow frameworks to define behavior (like @Autowired in Spring).
  • Reduce boilerplate code and improve maintainability.
  • They are essential in modern Java development, especially when working with tools like Spring, JUnit, and Hibernate.
Scroll to Top