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?
Compile-Time Checking – Helps compiler detect errors.
Code Documentation – Provides extra information.
Runtime Processing – Frameworks like Spring, Hibernate, and JUnit use annotations.
2. Built-in Annotations in Java
| Annotation | Description |
|---|---|
@Override | Checks if a method overrides a superclass method |
@Deprecated | Marks a method/class as outdated |
@SuppressWarnings | Suppresses compiler warnings |
@FunctionalInterface | Marks an interface as functional (for lambdas) |
@SafeVarargs | Suppresses warnings for variable arguments (varargs) |
Example: @Override
@Overrideensures 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-Annotation | Description |
|---|---|
@Retention | How long annotation is retained (SOURCE, CLASS, RUNTIME) |
@Target | Where annotation can be applied (METHOD, FIELD, TYPE, etc.) |
@Documented | Include annotation in Javadoc |
@Inherited | Allows annotation to be inherited by subclasses |
Summary
Annotations = Metadata for code
Types: Built-in (
@Override,@Deprecated) and CustomMeta-Annotations control behavior of annotations
Used in compile-time checking, documentation, and runtime frameworks
