Java
Module 28: Java Reflection APIBeginner22 min read

Reflection API & Bytecode Inspection

Use Class.forName, inspect declared methods and fields dynamically, and understand how frameworks like Spring and JUnit rely on reflection.

Key Takeaways & Core Concepts
  • Spring: Scans classes for @Component/@Service, inspects constructors, and injects dependencies dynamically.
  • Hibernate / JPA: Reads @Entity and @Column annotations to map database rows to Java objects.
  • JUnit: Discovers and invokes @Test methods automatically.
  • Jackson: Serializes and deserializes POJOs/Records to JSON.

What is Reflection?

Reflection (java.lang.reflect) allows a running Java program to inspect and manipulate its own classes, methods, fields, constructors, and annotations at runtime—even without knowing their names at compile time!

Inspecting Declared Methods at Runtime
1import java.lang.reflect.Method;
2
3public class Main {
4 public void greet() {}
5 public int add(int a, int b) { return a + b; }
6
7 public static void main(String[] args) {
8 for (Method m : Main.class.getDeclaredMethods()) {
9 System.out.println("Method: " + m.getName() + " (params: " + m.getParameterCount() + ")");
10 }
11 }
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: `getDeclaredMethods()` inspects methods declared directly on the class.

How Frameworks Use Reflection

  • Spring: Scans classes for @Component/@Service, inspects constructors, and injects dependencies dynamically.
  • Hibernate / JPA: Reads @Entity and @Column annotations to map database rows to Java objects.
  • JUnit: Discovers and invokes @Test methods automatically.
  • Jackson: Serializes and deserializes POJOs/Records to JSON.

Trade-offs & Strong Encapsulation (Java 17+)

Reflection bypasses compile-time type safety and disables some JIT inlining optimizations. Additionally, since Java 17, calling setAccessible(true) on JDK internal classes is blocked by the module system unless explicitly opened via --add-opens.

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)