DEV Community

Cover image for Reflection & Annotations in Java: Build a Mini Framework
naveen kumar
naveen kumar

Posted on

Reflection & Annotations in Java: Build a Mini Framework

If you've worked with frameworks like Spring or Hibernate, you've probably wondered at some point:

“How does this framework automatically execute code without me calling it?”

That’s where Reflection and Annotations come into play.

These two concepts are the core building blocks of modern Java frameworks. Once you understand them, you’ll stop just using frameworks — and start understanding how to build them.

In this article, we’ll break things down simply and build a mini framework step by step.

🎯 Why This Topic Matters

In today’s development world, writing basic code isn’t enough anymore.

✔ Developers are expected to understand framework internals
✔ Applications rely heavily on automation
✔ Clean and scalable architecture is a must
✔ Dynamic execution is everywhere

Learning reflection and annotations helps you level up from developer → engineer mindset.

🔍 What is Reflection in Java?

Reflection allows a Java program to inspect and manipulate itself at runtime.

Instead of directly calling methods, you can dynamically find and execute them.

⚙️ What You Can Do with Reflection

✔ Load classes dynamically
✔ Create objects without new
✔ Access private fields and methods
✔ Invoke methods at runtime
✔ Analyze class structure

💡 Example

Class<?> cls = Class.forName("MyService");
Object obj = cls.getDeclaredConstructor().newInstance();

Method method = cls.getDeclaredMethod("task1");
method.invoke(obj);
Enter fullscreen mode Exit fullscreen mode

👉 Here, the method is executed dynamically — no direct call.

🏷️ What are Annotations in Java?

Annotations are metadata tags added to code.

They don’t change logic directly but provide instructions that frameworks can use.

📌 Built-in Annotations

✔@ Override
✔@ Deprecated
✔@ SuppressWarnings

The real power comes from custom annotations.

🔗 Why Combine Reflection + Annotations?

This is where things get interesting.

Instead of manually calling methods:

service.task1();
service.task3();
Enter fullscreen mode Exit fullscreen mode

You can:

✔ Mark methods using annotations
✔ Detect them using reflection
✔ Execute them automatically

👉 This is how frameworks reduce boilerplate code.

🛠️ Build a Mini Java Framework (Step-by-Step)

Let’s build something practical.

🧩

Step 1: Create a Custom Annotation

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Execute {
}

Enter fullscreen mode Exit fullscreen mode

✔ Available at runtime
✔ Applied only to methods

🧪 Step 2: Create a Service Class

public class MyService {

    @Execute
    public void task1() {
        System.out.println("Task 1 executed");
    }

    public void task2() {
        System.out.println("Task 2 executed");
    }

    @Execute
    public void task3() {
        System.out.println("Task 3 executed");
    }
}

Enter fullscreen mode Exit fullscreen mode

✔ Only annotated methods should run

⚙️ Step 3: Build the Framework Engine

import java.lang.reflect.Method;

public class MiniFramework {

    public static void run(Object obj) throws Exception {
        Class<?> cls = obj.getClass();

        for (Method method : cls.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Execute.class)) {
                method.invoke(obj);
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

✔ Scans methods
✔ Checks annotation
✔ Executes dynamically

▶️ Step 4: Run the Framework

public class Main {
    public static void main(String[] args) throws Exception {
        MyService service = new MyService();
        MiniFramework.run(service);
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ Output
Task 1 executed
Task 3 executed

👉 Only annotated methods are executed.

🌍 Real-World Usage

Once you understand this, you’ll see it everywhere:

🌱 Spring Framework

✔ Dependency Injection
✔ Bean scanning
✔ Auto configuration

🗄️ Hibernate

✔ Database mapping
✔ Entity handling

🧪 JUnit

✔ Test execution using annotations

✅ Advantages

✔ Dynamic behavior
✔ Less boilerplate code
✔ Better scalability
✔ Cleaner architecture
✔ Foundation for frameworks

⚠️ Common Mistakes

✔ Forgetting RetentionPolicy.RUNTIME
✔ Overusing reflection (performance issues)
✔ Poor exception handling
✔ Overcomplicating annotations

🧠 Best Practices

✔ Use reflection only when necessary
✔ Cache reflective operations
✔ Keep annotations simple
✔ Follow clean architecture principles

FAQs

🤔 What is reflection in Java?

✔ It allows runtime inspection and execution of classes and methods.

🤔 Why use annotations?

✔ They provide metadata for frameworks to process code.

🤔 Is reflection slow?

✔ Yes, compared to direct calls — use carefully.

🤔 Where is it used?

✔ Spring, Hibernate, JUnit, and enterprise apps.

🤔 Can beginners learn it?

✔ Yes, with practice and real examples.

🏁 Final Thoughts

Reflection and annotations are not just “advanced topics” — they are core concepts behind modern Java development.

✔ They help you understand frameworks
✔ They improve your coding approach
✔ They enable you to build scalable systems

Top comments (0)