Java.Core.Explain the use of annotations in Java. Provide examples.

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:

AnnotationPurpose
@OverrideEnsures method overrides a superclass method
@DeprecatedMarks method/class as outdated (generates warnings)
@SuppressWarningsSuppresses compiler warnings
@FunctionalInterfaceMarks an interface as a functional interface
@SafeVarargsSuppresses unchecked warnings for varargs
@Retention, @TargetUsed 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:

  1. Define an annotation using @interface
  2. Use meta-annotations like @Retention and @Target
  3. 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)

AnnotationPurpose
@RetentionControls lifecycle (Compile-time, Class-file, Runtime)
@TargetSpecifies where annotation can be applied (Class, Method, Field, etc.)
@InheritedAllows annotation to be inherited by subclasses
@DocumentedMakes 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

TypeExamplePurpose
Built-in@Override, @DeprecatedCompiler-level hints
Custom@AuthorDefine metadata for classes/methods
Framework-specific@RestController, @EntityUsed in Spring, JPA, etc.
Meta-Annotations@Retention, @TargetControls 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.

This entry was posted in Без рубрики. Bookmark the permalink.