Java Reflection API: Dynamic Inspection, Private Fields & Methods

Reflection is Java's ability to inspect and modify classes, interfaces, constructors, methods, and fields at runtime without knowing their names at compile time. Frameworks like Spring Boot, Hibernate, and JUnit rely on Reflection to automatically instantiate beans, map database tables, and run unit tests marked with @Test.

1. Obtaining the Class Object

Every loaded type in the JVM is represented by a unique singleton instance of java.lang.Class. You can obtain it in three ways:

public class ReflectionClassDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        // Way 1: Via .class syntax (fastest, compile-time)
        Class clazz1 = String.class;

        // Way 2: Via getClass() on an existing instance
        String text = "Veewom";
        Class clazz2 = text.getClass();

        // Way 3: Via Class.forName() using fully-qualified name (dynamic)
        Class clazz3 = Class.forName("java.lang.String");

        System.out.println("Are all 3 class references identical? " + 
            (clazz1 == clazz2 && clazz2 == clazz3)); // Prints: true
    }
}

2. Inspecting Fields, Methods, and Constructors

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class InspectDemo {
    public static void main(String[] args) {
        Class clazz = Math.class;

        System.out.println("Class Name: " + clazz.getName());
        System.out.println("Is Interface: " + clazz.isInterface());
        System.out.println("Modifiers: " + Modifier.toString(clazz.getModifiers()));

        System.out.println("\nDeclared Methods:");
        Method[] methods = clazz.getDeclaredMethods();
        for (int i = 0; i < Math.min(5, methods.length); i++) {
            System.out.println("  " + methods[i].getReturnType().getSimpleName() + " " + 
                               methods[i].getName() + "()");
        }
    }
}

3. Accessing & Modifying Private Fields at Runtime

Reflection can bypass Java language access controls using setAccessible(true) (though Java 9+ Module System restricts this across strongly encapsulated packages):

import java.lang.reflect.Field;

class SecretVault {
    private String secretPin = "7492-Secure";
    
    public void printVaultStatus() {
        System.out.println("Vault PIN: " + secretPin);
    }
}

public class BreakEncapsulation {
    public static void main(String[] args) throws Exception {
        SecretVault vault = new SecretVault();
        vault.printVaultStatus(); // Prints: 7492-Secure

        // Access private field using Reflection
        Field pinField = SecretVault.class.getDeclaredField("secretPin");
        
        // Suppress Java language access checking
        pinField.setAccessible(true);
        
        // Inspect current private value
        System.out.println("Hacked Value: " + pinField.get(vault));

        // Overwrite private field value!
        pinField.set(vault, "9999-OVERRIDDEN");
        
        vault.printVaultStatus(); // Prints: 9999-OVERRIDDEN!
    }
}

4. Dynamic Method Invocation

import java.lang.reflect.Method;

public class DynamicInvoke {
    public static void main(String[] args) throws Exception {
        Class strClass = String.class;
        
        // Look up: public String toUpperCase()
        Method toUpperMethod = strClass.getMethod("toUpperCase");
        
        // Invoke on instance "hello veewom"
        Object result = toUpperMethod.invoke("hello veewom");
        System.out.println("Dynamic Result: " + result); // Prints: HELLO VEEWOM
    }
}

Pros and Cons of Reflection

AdvantagesDisadvantages
Enables dynamic dependency injection (Spring)Performance penalty (no JIT inlining or caching)
Permits plug-in architectures & visual GUI buildersBypasses compile-time type verification
Enables automated JSON/XML object serializersBreaks encapsulation (modifying private fields)
Powers testing frameworks (Mocking, JUnit)Restricted in Java 9+ Modular systems
BCA / University Exam Corner
  • Viva Question: What is the difference between getFields() and getDeclaredFields()?
    Answer: getFields() returns all public fields of the class and all its superclasses. getDeclaredFields() returns all fields (private, protected, default, and public) declared explicitly by that class, but excludes inherited fields.
  • Exam Distinction: Always note that Reflection should be reserved for framework infrastructure and avoided in standard business domain logic.

Frequently Asked Questions (FAQ)

Q1. What is the Java Reflection API and where is it used in production?
Reflection is a capability in java.lang.reflect that allows an executing Java program to inspect and manipulate its own classes, constructors, methods, and fields dynamically at runtime. It is the fundamental mechanism behind major enterprise frameworks including Spring Boot (dependency injection), Hibernate (ORM database mapping), Jackson (JSON serialization), and JUnit (test discovery).
Q2. What are the three ways to obtain a Class object in Java?
1. Class literal: Class c = String.class; 2. Instance method: Class c = myObj.getClass(); 3. Dynamic loading: Class c = Class.forName("java.lang.String");.
Q3. What are the major drawbacks or dangers of using Reflection?
1. Performance overhead (dynamic resolution bypasses JIT compiler optimizations), 2. Security vulnerabilities and loss of encapsulation (breaking private modifiers), 3. Loss of compile-time type safety (errors surface at runtime instead of compile time).

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java Annotations →

Processing custom metadata using Reflection.

JVM Architecture →

How ClassLoader loads Class metadata.

Access Modifiers →

Private, protected, and public encapsulation.

Design Patterns →

Factory and Proxy patterns via Reflection.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!