Annotations
Built-in annotations, custom annotations, meta-annotations, retention policies
- Understand what annotations are and why they exist
- Use built-in annotations: @Override, @Deprecated, @SuppressWarnings
- Create custom annotations with elements and defaults
- Apply meta-annotations: @Retention, @Target, @Inherited
Series:
Java Core Concepts | Chapter: Annotations Audience: Intermediate Java Developers Prerequisites: Java Reflection (required — annotations are accessed via reflection at runtime) Coverage: What Annotations Are, Predefined Annotations, Meta-Annotations, Custom Annotations, Heap Pollution, Repeatable Annotations
Table of Contents
- Custom (User-Defined) Annotations
- Accessing Annotations via Reflection
- Interview Question Bank
- Master Summary
Annotation Taxonomy Mind Map
1. What is an Annotation?
Definition
An annotation is a form of metadata added to Java code — classes, methods, fields, parameters, etc. — that provides information to the compiler, JVM, or frameworks at compile time or runtime.
Key Properties
| Property | Detail |
|---|---|
| Syntax | Always preceded by @ (at the rate) symbol |
| Usage | Optional — code works without annotations; they add information, not logic |
| Applies to | Classes, interfaces, methods, fields, parameters, constructors, local variables, packages, other annotations |
| Accessed via | Reflection at runtime (when RetentionPolicy.RUNTIME is used) |
| Relationship to metadata | Annotations ARE metadata — data about the code |
Real-World Analogy
Think of annotations like sticky notes on a physical document. The document (Java code) works without them — but the sticky notes provide extra instructions to whoever processes the document (compiler, JVM, or frameworks).
A Familiar Example `@Override`
1interface Bird {2 void canFly();3}4
5class Eagle implements Bird {6
7 @Override // This is an annotation8 public void canFly() {9 System.out.println("Eagle flies");10 }11}@Overrideis metadata telling the compiler: "Verify that this method actually overrides something from a parent class or interface."- If no matching method exists in the parent, the compiler throws an error.
- If you remove
@Override, the code still compiles — but you lose the safety check.
How Annotations Work Internally
2. Categories of Annotations
| Category | Sub-category | Examples |
|---|---|---|
| Predefined | Used on Java code | @Deprecated, @Override, @SuppressWarnings, @FunctionalInterface, @SafeVarargs |
| Predefined | Meta-annotations | @Target, @Retention, @Documented, @Inherited, @Repeatable |
| Custom | User-defined | Any @interface you create yourself |
3. Predefined Annotations Used on Java Code
`@Deprecated`
What It Does
Marks a class, method, constructor, field, or package as deprecated — meaning it is no longer recommended for use, no further development will happen on it, and an alternative may exist.
Effect
Anyone who uses a deprecated element gets a compiler warning.
Where It Can Be Applied
Constructor, field, local variable, method, package, parameter, type (class/interface/enum).
Code Example
1class Mobile {2
3 @Deprecated4 void oldSendMessage() {5 System.out.println("Old SMS method");6 }7
8 void newSendMessage() {9 System.out.println("New method — use this instead");10 }11}12
13public class Main {14 public static void main(String[] args) {15 Mobile m = new Mobile();16 m.oldSendMessage(); // ⚠️ Compiler warning: 'oldSendMessage()' is deprecated17 m.newSendMessage(); // ✅ No warning18 }19}Compiler Warning:
1warning: [deprecation] oldSendMessage() in Mobile has been deprecatedBest Practice
When deprecating, add a Javadoc comment explaining the alternative:
1/**2 * @deprecated Use {@link #newSendMessage()} instead.3 */4@Deprecated5void oldSendMessage() { ... }`@Override`
What It Does
Tells the compiler: "Verify that this method is actually overriding a method from a parent class or interface." If no such method exists in the parent, the compiler throws an error.
Effect
Compile-time safety check — prevents silent bugs where you think you're overriding but are actually creating a new method (e.g., due to a typo in the method name).
Where It Can Be Applied
Methods only.
Code Example
1interface Bird {2 void canFly();3}4
5class Eagle implements Bird {6 @Override7 public void canFly() { // ✅ Correct override8 System.out.println("Eagle flies");9 }10}11
12class Sparrow implements Bird {13 @Override14 public void canFly1() { // ❌ Compile error: method does not override or implement a method15 System.out.println("Sparrow flies");16 }17}@Override when you intend to override a method. It catches refactoring mistakes where a parent method signature changes and the child method silently stops being an override.`@SuppressWarnings`
What It Does
Instructs the compiler to ignore specific warnings for the annotated element.
Where It Can Be Applied
Field, method, parameter, constructor, local variable, type.
Common Warning Keys
| Warning Key | Suppresses |
|---|---|
"deprecation" | Warnings about using deprecated code |
"unused" | Warnings about unused variables, methods |
"unchecked" | Warnings about unchecked type operations |
"all" | All compiler warnings |
"rawtypes" | Warnings about using raw generic types |
Code Example
1class Mobile {2 @Deprecated3 void oldMethod() { }4}5
6public class Main {7
8 // Suppress warning for this specific method9 @SuppressWarnings("deprecation")10 void useOldMethod() {11 Mobile m = new Mobile();12 m.oldMethod(); // No warning shown13 }14
15 // Suppress ALL warnings for this class16 @SuppressWarnings("all")17 void anotherMethod() {18 Mobile m = new Mobile();19 m.oldMethod(); // No warning shown20 int unused = 5; // No "unused" warning either21 }22}@SuppressWarnings carefully. Warnings exist for good reasons — suppressing them blindly (especially "all") can hide real bugs. For example, suppressing a warning about dividing by zero could cause a runtime ArithmeticException that you'd have been warned about.Applied at Class Level vs Method Level
1// Method level — suppresses only for this method2@SuppressWarnings("deprecation")3void specificMethod() { ... }4
5// Class level — suppresses for ALL methods in the class6@SuppressWarnings("deprecation")7public class MyClass { ... }`@FunctionalInterface`
What It Does
Marks an interface as a functional interface — one that has exactly one abstract method. The compiler enforces this constraint: if you add a second abstract method, it is a compile error.
Where It Can Be Applied
Type (interface, class, enum) — practically only meaningful on interfaces.
Code Example
1@FunctionalInterface2interface MyFunction {3 void execute(); // One abstract method — OK4
5 // void anotherMethod(); // ❌ Compile error: Multiple non-overriding abstract methods6}1// Without @FunctionalInterface — no compile-time enforcement2interface MyFunction {3 void execute();4 void another(); // ✅ Compiles — but is no longer a functional interface5}6
7// With @FunctionalInterface — compiler enforces the single-abstract-method rule8@FunctionalInterface9interface MyFunction {10 void execute();11 void another(); // ❌ Compile error — @FunctionalInterface constraint violated12}@FunctionalInterface can have multiple default/static methods as long as it has exactly one abstract method.`@SafeVarargs`
What It Does
Suppresses the heap pollution warning that appears when a method or constructor accepts variable arguments (varargs) of a generic type.
Where It Can Be Applied
Methods and constructors that accept varargs. The method must be either:
staticfinalprivate(Java 9+)
Why These Restrictions?
Because these modifiers prevent the method from being overridden. If a parent method has @SafeVarargs and a child overrides it, the child might miss the annotation — losing the safety guarantee. Methods that can't be overridden don't have this problem.
Code Example
1class Example {2
3 // Without @SafeVarargs — compiler shows heap pollution warning4 @SafeVarargs5 public static void printValues(List<Integer>... lists) {6 for (List<Integer> list : lists) {7 System.out.println(list);8 }9 }10}Without @SafeVarargs:
1warning: Possible heap pollution from parameterized vararg type List<Integer>With @SafeVarargs: The warning is suppressed. Use only when you are certain the method does not actually cause heap pollution.
@SafeVarargs requires understanding heap pollution, which is covered in depth in Section 4.4. Heap Pollution Deep Dive
What is Heap Pollution?
Heap pollution
occurs when a variable of a parameterized type (like List) holds a reference to an object that is not of that type (like a List).
Normal (Non-Polluted) Heap
1Stack Heap2──── ────3List<Integer> myList ──► [1, 2, 3, 4, 5] ← correct: Integer valuesPolluted Heap
1Stack Heap2──── ────3List<Integer> myList ──► ["hello", "world"] ← polluted: String values in Integer list!Why Does Varargs Cause Heap Pollution Risk?
Variable arguments (T... args) are internally converted to an array by Java. Arrays and generics don't mix perfectly — and through the Object[] loophole, you can accidentally store wrong types.
Step-by-Step Example
1import java.util.*;2
3class Example {4
5 // Accepts variable number of List<Integer> arguments6 static void printLogValues(List<Integer>... logNumberLists) {7
8 // Step 1: Store varargs in Object array (this is the dangerous step)9 Object[] objectArray = logNumberLists; // ⚠️ Possible heap pollution here10
11 // Step 2: Create a List<String>12 List<String> stringList = new ArrayList<>();13 stringList.add("hello");14 stringList.add("world");15
16 // Step 3: HEAP POLLUTION — putting a List<String> where List<Integer> is expected17 objectArray[0] = stringList; // No compile error here!18
19 // Step 4: This will cause ClassCastException at runtime20 Integer firstValue = logNumberLists[0].get(0); // ❌ ClassCastException!21 }22
23 public static void main(String[] args) {24 List<Integer> listA = Arrays.asList(1, 2, 3);25 printLogValues(listA); // ❌ ClassCastException at runtime26 }27}What Happened?
The Warning and How to Suppress It
Whenever you pass a generic type as varargs, the compiler warns:
1Possible heap pollution from parameterized vararg type List<Integer>If you have verified your code does not actually cause heap pollution, suppress with:
1@SafeVarargs2public static void printLogValues(List<Integer>... logNumberLists) {3 // Safe usage — no Object[] tricks4 for (List<Integer> list : logNumberLists) {5 System.out.println(list);6 }7}@SafeVarargs only suppresses the warning — it does not prevent heap pollution from actually occurring. Only use it when you are genuinely certain your varargs usage is safe.5. Meta-Annotations Annotations on Annotations
Meta-annotations are annotations applied on top of other annotations to define their behavior: where they can be used, how long they live, whether they appear in docs, etc.
`@Target`
What It Does
Specifies where an annotation can be applied — methods only, fields only, classes only, etc.
Element Types
ElementType | Where the annotation can be applied |
|---|---|
TYPE | Class, interface, enum |
FIELD | Instance variable / field |
METHOD | Method |
PARAMETER | Method parameter |
CONSTRUCTOR | Constructor |
LOCAL_VARIABLE | Local variable inside a method |
ANNOTATION_TYPE | Another annotation (makes it a meta-annotation) |
PACKAGE | Package |
TYPE_PARAMETER | Generic type parameter (e.g., T in class Foo) |
TYPE_USE | Any use of a type (Java 8+) — e.g., before String in List |
How `@Override` Uses `@Target`
1// How @Override is defined inside Java (simplified):2@Target(ElementType.METHOD) // Can only be used on methods3@Retention(RetentionPolicy.SOURCE) // Not stored in .class file4public @interface Override {5}How `@SafeVarargs` Uses `@Target`
1// How @SafeVarargs is defined (simplified):2@Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) // Constructor or Method only3@Retention(RetentionPolicy.RUNTIME)4public @interface SafeVarargs {5}`ANNOTATION_TYPE` Making a Meta-Annotation
If you add ElementType.ANNOTATION_TYPE to your annotation's @Target, your annotation can be applied on other annotations:
1@Target(ElementType.ANNOTATION_TYPE) // Can be used ON annotations2public @interface MyMetaAnnotation {3}4
5@MyMetaAnnotation // Applying it on another annotation6public @interface SomeAnnotation {7}`@Retention`
What It Does
Specifies how long (at what stage of the Java lifecycle) an annotation is retained/available.
Retention Policies
RetentionPolicy | Where annotation lives | Accessible via Reflection? |
|---|---|---|
SOURCE | Only in .java source — discarded by compiler | ❌ No |
CLASS | In .java and .class files — ignored by JVM at runtime | ❌ No |
RUNTIME | In .java, .class, and available to JVM at runtime | ✅ Yes |
Lifecycle Diagram
`@Override` Uses `SOURCE` Why?
1@Retention(RetentionPolicy.SOURCE) // Discarded after compilation2public @interface Override { }@Override is only needed during compilation to verify the method signature. Once compiled, the bytecode is just a regular method — the annotation serves no runtime purpose, so discarding it saves space.
Code Example Runtime Retention
1import java.lang.annotation.*;2
3// Custom annotation with RUNTIME retention4@Retention(RetentionPolicy.RUNTIME)5@Target(ElementType.TYPE)6public @interface MyAnnotation { }7
8@MyAnnotation9class TestClass { }10
11public class Main {12 public static void main(String[] args) {13
14 // With RUNTIME retention — annotation is accessible15 MyAnnotation annotation = TestClass.class.getAnnotation(MyAnnotation.class);16 System.out.println(annotation); // @MyAnnotation()17
18 // Without RUNTIME retention — annotation is NOT accessible19 // Returns null20 }21}@MyAnnotation()
Output (without RUNTIME — e.g., CLASS or SOURCE):
1null`@Documented`
What It Does
By default, annotations are not included in the generated Javadoc. @Documented changes this — any annotation marked with @Documented will appear in the Javadoc of the elements it annotates.
Comparison
1// @Override does NOT have @Documented2// → @Override does not appear in Javadoc of overriding methods3
4// @SafeVarargs HAS @Documented5// → @SafeVarargs appears in Javadoc of annotated methodsWhen to Use
Use @Documented on annotations that are part of your public API and should be visible to users of your library/framework through the generated documentation.
`@Inherited`
What It Does
By default, annotations applied to a parent class are not available to child classes. @Inherited changes this — the annotation propagates to subclasses automatically.
Default Behavior (Without `@Inherited`)
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.TYPE)3public @interface MyAnnotation { } // No @Inherited4
5@MyAnnotation6class Parent { }7
8class Child extends Parent { } // Does NOT have @MyAnnotation9
10public class Main {11 public static void main(String[] args) {12 MyAnnotation a = Child.class.getAnnotation(MyAnnotation.class);13 System.out.println(a); // null — not inherited14 }15}With `@Inherited`
1@Inherited // Added here2@Retention(RetentionPolicy.RUNTIME)3@Target(ElementType.TYPE)4public @interface MyAnnotation { }5
6@MyAnnotation7class Parent { }8
9class Child extends Parent { } // NOW has @MyAnnotation through inheritance10
11public class Main {12 public static void main(String[] args) {13 MyAnnotation a = Child.class.getAnnotation(MyAnnotation.class);14 System.out.println(a); // @MyAnnotation() — inherited!15 }16}`@Inherited` Behavior Summary
| Scenario | Annotation on Child? |
|---|---|
No @Inherited on annotation | ❌ Child does not get it |
@Inherited on annotation, annotation on Parent | ✅ Child gets it automatically |
@Inherited but annotation directly on Child too | ✅ Child's own annotation takes precedence |
@Inherited only works with class inheritance (extends). It does NOT propagate through interface implementation.`@Repeatable`
What It Does
By default, you cannot apply the same annotation twice to the same element. @Repeatable (introduced in Java 8) removes this restriction, allowing an annotation to be used multiple times on the same target.
The Problem Without `@Repeatable`
1@Category(name = "Bird")2@Category(name = "LivingThing") // ❌ Compile error — duplicate annotation3class Eagle { }Two-Step Solution
Step 1: Mark the annotation as repeatable and specify a container:
1@Repeatable(Categories.class) // Step 1 — mark as repeatable; name the container2@Retention(RetentionPolicy.RUNTIME)3@Target(ElementType.TYPE)4public @interface Category {5 String name(); // Annotation member6}Step 2: Create the container annotation (holds an array of the repeatable annotation):
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.TYPE)3public @interface Categories {4 Category[] value(); // Must be named "value" and be an array of the repeatable annotation5}Usage:
1@Category(name = "Bird")2@Category(name = "LivingThing")3@Category(name = "Carnivorous")4class Eagle { } // ✅ Now valid — @Repeatable allows thisAccessing Repeated Annotations via Reflection:
1public class Main {2 public static void main(String[] args) {3 Category[] categories = Eagle.class.getAnnotationsByType(Category.class);4
5 for (Category cat : categories) {6 System.out.println(cat.name());7 }8 }9}Bird LivingThing Carnivorous
How It Works Internally
When you apply @Category three times, the compiler wraps them all into the container:
1// What you write:2@Category(name = "Bird")3@Category(name = "LivingThing")4@Category(name = "Carnivorous")5class Eagle { }6
7// What the compiler actually stores:8@Categories({9 @Category(name = "Bird"),10 @Category(name = "LivingThing"),11 @Category(name = "Carnivorous")12})13class Eagle { }Diagram Container Wrapping
Meta-Annotations Summary Table
| Meta-Annotation | Purpose | Target |
|---|---|---|
@Target | Defines WHERE the annotation can be applied | Annotations |
@Retention | Defines HOW LONG the annotation is retained | Annotations |
@Documented | Makes the annotation appear in Javadoc | Annotations |
@Inherited | Allows annotation to propagate to subclasses | Annotations on classes |
@Repeatable | Allows same annotation to be used multiple times | Annotations |
6. Custom (User-Defined) Annotations
Creating an Annotation
Annotations are created using the @interface keyword (not to be confused with a regular interface):
1public @interface MyAnnotation {2 // annotation members go here3}Form 1 Empty Annotation (Marker Annotation)
No members — just used as a flag/marker:
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.TYPE)3public @interface MyAnnotation {4 // No members — just a marker5}6
7@MyAnnotation8class TestClass { }Form 2 Annotation with Members
Members look like methods but have no parameters and no body. They define the data the annotation can carry:
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.TYPE)3public @interface MyCustomAnnotation {4 String name(); // String member5 int version(); // int member6}7
8// Usage — must provide values for all members without defaults9@MyCustomAnnotation(name = "TestClass", version = 1)10class TestClass { }Annotation Member Rules
| Rule | Detail |
|---|---|
| Parameters | ❌ Members cannot have parameters |
| Body | ❌ Members cannot have a body |
| Return type | Only: primitive types, String, Class, enum, another annotation, or arrays of these |
| Custom objects | ❌ Cannot use custom class objects as return type |
| Naming | Conventionally used as value() for the single most important member |
Valid Member Types
1public @interface Example {2 int count(); // ✅ primitive3 String label(); // ✅ String4 Class<?> type(); // ✅ Class5 MyEnum status(); // ✅ enum6 OtherAnnotation meta(); // ✅ another annotation7 int[] numbers(); // ✅ array of primitive8 String[] tags(); // ✅ array of String9 Class<?>[] types(); // ✅ array of Class10
11 // Object custom(); ❌ Cannot use custom class12}Form 3 Annotation with Default Values
Members can have default values using the default keyword:
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.TYPE)3public @interface MyAnnotation {4 String name() default "Hello"; // default value5 int version() default 1;6}7
8// Usage — can omit members that have defaults9@MyAnnotation // ✅ name="Hello", version=110class ClassA { }11
12@MyAnnotation(name = "SJ") // ✅ name="SJ", version=113class ClassB { }14
15@MyAnnotation(name = "SJ", version = 2) // ✅ name="SJ", version=216class ClassC { }Complete Custom Annotation Example
1import java.lang.annotation.*;2
3// Step 1 — Create the annotation4@Retention(RetentionPolicy.RUNTIME)5@Target({ElementType.TYPE, ElementType.METHOD})6@Documented7public @interface ApiInfo {8 String author() default "Unknown";9 String version() default "1.0";10 String description(); // No default — must always be provided11 boolean deprecated() default false;12}13
14// Step 2 — Use it15@ApiInfo(16 author = "Shreyansh",17 version = "2.0",18 description = "Main service class for user management"19)20public class UserService {21
22 @ApiInfo(23 description = "Fetches user by ID",24 deprecated = true25 )26 public void getUserById(int id) { }27}7. Accessing Annotations via Reflection
Overview
Annotations with RetentionPolicy.RUNTIME can be read at runtime using Java's Reflection API.
Key Reflection Methods for Annotations
| Method | What it does |
|---|---|
clazz.getAnnotation(AnnotationType.class) | Returns the annotation of the given type if present; null otherwise |
clazz.getAnnotations() | Returns all annotations on the element |
clazz.getDeclaredAnnotations() | Returns all annotations directly on the element (excluding inherited) |
clazz.getAnnotationsByType(AnnotationType.class) | Returns array — useful for @Repeatable annotations |
clazz.isAnnotationPresent(AnnotationType.class) | Returns true if the annotation is present |
Code Example Reading a Custom Annotation
1import java.lang.annotation.*;2
3@Retention(RetentionPolicy.RUNTIME)4@Target(ElementType.TYPE)5@interface MyAnnotation {6 String name() default "default";7}8
9@MyAnnotation(name = "TestClass")10class TestClass { }11
12public class Main {13 public static void main(String[] args) {14 // Get the Class object15 Class<?> clazz = new TestClass().getClass();16
17 // Check if annotation is present18 if (clazz.isAnnotationPresent(MyAnnotation.class)) {19 // Get the annotation20 MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);21 System.out.println("Annotation found: " + annotation);22 System.out.println("name = " + annotation.name());23 } else {24 System.out.println("Annotation not found");25 }26 }27}Annotation found: @MyAnnotation(name="TestClass") name = TestClass
What Happens Without `RUNTIME` Retention
1@Retention(RetentionPolicy.CLASS) // or SOURCE — NOT RUNTIME2@Target(ElementType.TYPE)3@interface MyAnnotation { }4
5@MyAnnotation6class TestClass { }7
8public class Main {9 public static void main(String[] args) {10 MyAnnotation a = TestClass.class.getAnnotation(MyAnnotation.class);11 System.out.println(a); // null — annotation not available at runtime12 }13}null
Reflection + Repeatable Annotations
1Category[] categories = Eagle.class.getAnnotationsByType(Category.class);2// Returns all @Category annotations applied to EagleUse getAnnotationsByType() (not getAnnotation()) for repeatable annotations, since there may be multiple instances.
8. Interview Question Bank
Annotation Basics
| Question | Key Answer |
|---|---|
| What is an annotation in Java? | Metadata added to Java code using @; optional; used by compiler/JVM/frameworks for processing |
| How do you denote an annotation? | Always starts with @ — e.g., @Override, @Deprecated |
| How are annotations accessed at runtime? | Via Java Reflection API when RetentionPolicy.RUNTIME is set |
| Are annotations mandatory? | No — they're optional metadata; removing them doesn't break code |
| Where can annotations be applied? | Classes, methods, fields, parameters, constructors, local variables, packages, and other annotations |
Predefined Annotations
| Question | Key Answer |
|---|---|
What does @Deprecated do? | Marks element as outdated; compiler shows warning when used |
What does @Override do? | Tells compiler to verify the method actually overrides a parent method; compile error if not |
What does @SuppressWarnings do? | Suppresses specific compiler warnings; use carefully as warnings may prevent bugs |
What does @FunctionalInterface do? | Enforces that interface has exactly one abstract method; compile error if more are added |
What does @SafeVarargs do? | Suppresses heap pollution warning for varargs methods; only on static/final/private methods |
Heap Pollution
| Question | Key Answer |
|---|---|
| What is heap pollution? | When a variable of parameterized type (e.g., List) holds reference to wrong type object (e.g., List) |
| What causes heap pollution with varargs? | Varargs become Object[] internally; allows storing wrong types; leads to ClassCastException at runtime |
| How to suppress heap pollution warning? | @SafeVarargs on a static, final, or private method that accepts varargs |
Meta-Annotations
| Question | Key Answer |
|---|---|
| What is a meta-annotation? | An annotation applied on another annotation |
What does @Target do? | Specifies where an annotation can be applied (method, field, type, etc.) |
What does @Retention do? | Specifies how long the annotation is retained: SOURCE, CLASS, or RUNTIME |
What is the difference between RetentionPolicy.CLASS and RUNTIME? | CLASS is in bytecode but ignored by JVM; RUNTIME is in bytecode AND available via reflection |
Why does @Override use RetentionPolicy.SOURCE? | It's only needed at compile time; no need to store in bytecode |
What does @Documented do? | Makes annotation appear in Javadoc; by default annotations are excluded |
What does @Inherited do? | Makes annotation on parent class propagate to subclasses; off by default |
What does @Repeatable do? | Allows the same annotation to be applied multiple times to one element (Java 8+) |
How do you implement @Repeatable? | Two steps: (1) add @Repeatable(ContainerClass.class) to annotation, (2) create container annotation with AnnotationType[] value() |
Custom Annotations
| Question | Key Answer |
|---|---|
| How do you create a custom annotation? | public @interface AnnotationName { } — use @interface keyword |
| What types can annotation members have? | Primitives, String, Class, enum, another annotation, or arrays of these |
| Can annotation members have parameters? | No — they have no parameters and no body |
| How do you add a default value to an annotation member? | String name() default "hello"; |
| What is a marker annotation? | An annotation with no members — used just as a flag |
9. Master Summary
Quick Revision Bullets
What Annotations Are:
- ✅ Annotation = metadata added to Java code using
@symbol - ✅ Optional — does not change program logic directly; provides information to compiler/JVM/frameworks
- ✅ Can be applied to: classes, methods, fields, parameters, constructors, local variables, packages, and other annotations
- ✅ Accessed at runtime via Reflection — only if
RetentionPolicy.RUNTIMEis used
Predefined Annotations (on Java code):
- ✅
@Deprecated— marks element as outdated; compiler warning when used - ✅
@Override— compile-time check that method actually overrides a parent method; only on methods - ✅
@SuppressWarnings("key")— suppresses specific compiler warnings; use carefully - ✅
@FunctionalInterface— enforces exactly one abstract method; compile error if violated - ✅
@SafeVarargs— suppresses heap pollution warning on varargs methods; only onstatic/final/privatemethods (Java 9+: alsoprivate)
Heap Pollution:
- ✅ Heap pollution = variable of parameterized type holds reference to wrong type (e.g.,
ListholdsList) - ✅ Caused by the
Object[]loophole when varargs of generic type are used - ✅ Results in
ClassCastExceptionat runtime - ✅
@SafeVarargssuppresses the warning — use only when you've verified no actual pollution occurs
Meta-Annotations:
- ✅
@Target(ElementType.X)— restricts WHERE annotation can be applied - ✅
@Retention(RetentionPolicy.X)— controls HOW LONG annotation lives:SOURCE→CLASS→RUNTIME - ✅ Only
RUNTIMEretention allows reflection-based access - ✅
@Documented— includes annotation in Javadoc (excluded by default) - ✅
@Inherited— propagates annotation from parent class to subclasses (not via interface implementation) - ✅
@Repeatable(Java 8+) — allows same annotation multiple times; requires a container annotation withAnnotationType[] value()
Custom Annotations:
- ✅ Created with
public @interface AnnotationName { } - ✅ Members: look like methods, no parameters, no body; return type restricted to primitives/String/Class/enum/annotation/arrays of these
- ✅ Default values:
String name() default "hello"; - ✅ Combine with meta-annotations (
@Target,@Retention) to control usage and lifetime - ✅ Access at runtime via
clazz.getAnnotation(Type.class)orgetAnnotationsByType()for repeatable ones
@FunctionalInterface; covered in a dedicated video due to its importance in modern JavaEnd of Chapter — Java Annotations
Mastery check
How well can you recall this?
Finished this lesson?