Java Annotations

🏷️ Java Annotations

Annotations in Java are metadata that provide information about the code to the compiler or runtime environment.

  • Do not change program semantics directly

  • Help in compile-time checking, documentation, and runtime processing

  • Package: java.lang.annotation (for custom annotations)


 1. Why Use Annotations?

  1. Compile-Time Checking – Helps compiler detect errors.

  2. Code Documentation – Provides extra information.

  3. Runtime Processing – Frameworks like Spring, Hibernate, and JUnit use annotations.


 2. Built-in Annotations in Java

AnnotationDescription
@OverrideChecks if a method overrides a superclass method
@DeprecatedMarks a method/class as outdated
@SuppressWarningsSuppresses compiler warnings
@FunctionalInterfaceMarks an interface as functional (for lambdas)
@SafeVarargsSuppresses warnings for variable arguments (varargs)

Example: @Override


 

  • @Override ensures compile-time checking.

  • If method name is wrong, compiler will show an error.


Example: @Deprecated


 

  • Warns developers not to use old methods.


Example: @SuppressWarnings

  • Suppresses specific compiler warnings.


 3. Custom Annotations

You can create your own annotations using @interface.


 

  • @Retention(RetentionPolicy.RUNTIME) → Available at runtime

  • @Target(ElementType.METHOD) → Specifies applicable targets (methods, classes, fields, etc.)


4. Meta-Annotations

  • Annotations that describe other annotations:

Meta-AnnotationDescription
@RetentionHow long annotation is retained (SOURCE, CLASS, RUNTIME)
@TargetWhere annotation can be applied (METHOD, FIELD, TYPE, etc.)
@DocumentedInclude annotation in Javadoc
@InheritedAllows annotation to be inherited by subclasses

 Summary

  • Annotations = Metadata for code

  • Types: Built-in (@Override, @Deprecated) and Custom

  • Meta-Annotations control behavior of annotations

  • Used in compile-time checking, documentation, and runtime frameworks

You may also like...