Annotations are special markers (@AnnotationName
) added to classes, methods, variables, or parameters to provide metadata.
- They don’t affect program logic directly.
- They can be processed at compile-time (for warnings, code generation) or at runtime (for reflection-based frameworks like Spring, JPA).
✅ Why Use Annotations?
✔ Reduce boilerplate code
✔ Provide metadata to tools and frameworks
✔ Enable custom behaviors at compile-time or runtime
✔ Help code readability
📚 Common Built-in Annotations
Java provides several built-in annotations, categorized by purpose:
Annotation | Purpose |
---|---|
@Override | Ensures method overrides a superclass method |
@Deprecated | Marks method/class as outdated (generates warnings) |
@SuppressWarnings | Suppresses compiler warnings |
@FunctionalInterface | Marks an interface as a functional interface |
@SafeVarargs | Suppresses unchecked warnings for varargs |
@Retention , @Target | Used for custom annotations (explained below) |
🔎 Examples of Common Annotations
1️⃣ @Override
(Ensures method is correctly overridden)
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() { // Compiler checks correctness
System.out.println("Bark");
}
}
✅ If you misspell makeSound()
in Dog
, the compiler throws an error.
2️⃣ @Deprecated
(Marks outdated methods)
class OldAPI {
@Deprecated
void oldMethod() {
System.out.println("This method is deprecated");
}
}
✅ The compiler will warn that this method shouldn’t be used.
3️⃣ @SuppressWarnings
(Hides warnings)
@SuppressWarnings("unchecked") // Suppresses unchecked warnings
List rawList = new ArrayList(); // No generics warning
✅ Helps in cases where you intentionally bypass compiler checks.
🔥 Custom Annotations
You can create your own annotations to define metadata.
Steps:
- Define an annotation using
@interface
- Use meta-annotations like
@Retention
and@Target
- Apply it to classes, methods, or fields
Example: @Author
Custom Annotation
1️⃣ Define the annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) // Available at runtime
@Target(ElementType.TYPE) // Can only be applied to classes
@interface Author {
String name();
String date();
}
2️⃣ Apply the annotation
@Author(name = "Stanley", date = "2025-03-06")
public class MyBook {
// Class logic
}
3️⃣ Read annotation at runtime (Reflection API)
import java.lang.reflect.*;
public class AnnotationProcessor {
public static void main(String[] args) {
Class<MyBook> obj = MyBook.class;
if (obj.isAnnotationPresent(Author.class)) {
Author author = obj.getAnnotation(Author.class);
System.out.println("Author: " + author.name() + ", Date: " + author.date());
}
}
}
✅ Output:
Author: Stanley, Date: 2025-03-06
🛠 Meta-Annotations (Annotations for Annotations)
Annotation | Purpose |
---|---|
@Retention | Controls lifecycle (Compile-time, Class-file, Runtime) |
@Target | Specifies where annotation can be applied (Class, Method, Field, etc.) |
@Inherited | Allows annotation to be inherited by subclasses |
@Documented | Makes annotation appear in Javadocs |
🚀 Practical Uses of Annotations
✔ Spring Framework (@Service
, @Autowired
) – Dependency injection
✔ JPA/Hibernate (@Entity
, @Column
) – Database mapping
✔ JUnit (@Test
, @BeforeEach
) – Unit testing
✔ Lombok (@Getter
, @Setter
) – Auto-generate boilerplate code
📊 Summary Table
Type | Example | Purpose |
---|---|---|
Built-in | @Override , @Deprecated | Compiler-level hints |
Custom | @Author | Define metadata for classes/methods |
Framework-specific | @RestController , @Entity | Used in Spring, JPA, etc. |
Meta-Annotations | @Retention , @Target | Controls how annotations behave |
🎯 Final Pro Tips for Interviews
✅ Always mention built-in + custom annotations.
✅ Explain that annotations don’t affect runtime directly (except if used via reflection).
✅ Highlight real-world usage (Spring, Hibernate, JUnit).
✅ If asked “How are annotations processed?”, mention reflection + annotation processors.