---
title: "Processing Annotations Using Reflection in Java"  
description: "Processing Annotations Using Reflection in Java"  
author: "ICSM Computer"  
published: 2025-04-24  
updated: 2025-04-24  
canonical: https://www.mindstick.com/interview/34071/processing-annotations-using-reflection-in-java  
category: "java"  
tags: ["java"]  
reading_time: 4 minutes  

---

# Processing Annotations Using Reflection in Java

Once you've got defined and carried out custom annotations, you may use Java reflection to system them at runtime. This is especially useful in frameworks where you scan metadata to drive behavior (for example, dependency injection, configuration, validation).

## 1. Custom Annotation Example

Let's say we have a custom annotation for marking methods to be executed:

```java
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunMe {
    String message() default "Executing";
}
```

## 2. Class with Annotated Methods

```java
public class TaskRunner {
    @RunMe(message = "Start Task")
    public void start() {
        System.out.println("Starting...");
    }

    @RunMe
    public void process() {
        System.out.println("Processing...");
    }

    public void skipThis() {
        System.out.println("Not annotated");
    }
}
```

## 3. Processing Annotations with Reflection

You can now write a class that scans for methods with `@RunMe` and invokes them.

```java
import java.lang.reflect.Method;

public class AnnotationProcessor {
    public static void main(String[] args) {
        try {
            TaskRunner runner = new TaskRunner();
            Class<?> clazz = runner.getClass();

            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(RunMe.class)) {
                    RunMe annotation = method.getAnnotation(RunMe.class);
                    System.out.println("Invoking: " + method.getName());
                    System.out.println("  Message: " + annotation.message());

                    method.invoke(runner);  // Call the method dynamically
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

## Output:

```plaintext
Invoking: start
  Message: Start Task
Starting...
Invoking: process
  Message: Executing
Processing...
```

## 4. Key Reflection APIs Used

| Method | Description |
| --- | --- |
| `Class.getDeclaredMethods()` | Gets all declared methods in the class |
| `method.isAnnotationPresent()` | Checks if an annotation is present |
| `method.getAnnotation()` | Retrieves the annotation object |
| `method.invoke(obj)` | Dynamically calls the method on the object |

## 5. Use Cases in Real Projects

1. **JUnit**: Uses `@Test` to identify test methods.
2. **Spring**: Uses annotations like `@Autowired`, `@RequestMapping` and processes them at runtime.
3. **Hibernate**: Reads `@Entity`, `@Table`, etc., to map Java classes to database tables.

## Answers

### Answer by ICSM Computer

Once you've got defined and carried out custom annotations, you may use Java reflection to system them at runtime. This is especially useful in frameworks where you scan metadata to drive behavior (for example, dependency injection, configuration, validation).

## 1. Custom Annotation Example

Let's say we have a custom annotation for marking methods to be executed:

```java
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunMe {
    String message() default "Executing";
}
```

## 2. Class with Annotated Methods

```java
public class TaskRunner {
    @RunMe(message = "Start Task")
    public void start() {
        System.out.println("Starting...");
    }

    @RunMe
    public void process() {
        System.out.println("Processing...");
    }

    public void skipThis() {
        System.out.println("Not annotated");
    }
}
```

## 3. Processing Annotations with Reflection

You can now write a class that scans for methods with `@RunMe` and invokes them.

```java
import java.lang.reflect.Method;

public class AnnotationProcessor {
    public static void main(String[] args) {
        try {
            TaskRunner runner = new TaskRunner();
            Class<?> clazz = runner.getClass();

            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(RunMe.class)) {
                    RunMe annotation = method.getAnnotation(RunMe.class);
                    System.out.println("Invoking: " + method.getName());
                    System.out.println("  Message: " + annotation.message());

                    method.invoke(runner);  // Call the method dynamically
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

## Output:

```plaintext
Invoking: start
  Message: Start Task
Starting...
Invoking: process
  Message: Executing
Processing...
```

## 4. Key Reflection APIs Used

| Method | Description |
| --- | --- |
| `Class.getDeclaredMethods()` | Gets all declared methods in the class |
| `method.isAnnotationPresent()` | Checks if an annotation is present |
| `method.getAnnotation()` | Retrieves the annotation object |
| `method.invoke(obj)` | Dynamically calls the method on the object |

## 5. Use Cases in Real Projects

1. **JUnit**: Uses `@Test` to identify test methods.
2. **Spring**: Uses annotations like `@Autowired`, `@RequestMapping` and processes them at runtime.
3. **Hibernate**: Reads `@Entity`, `@Table`, etc., to map Java classes to database tables.


---

Original Source: https://www.mindstick.com/interview/34071/processing-annotations-using-reflection-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
