Java Reflection

Java Reflection

What is Reflection?

Reflection is Java's ability to look into and change classes, methods, fields, and constructors at runtime. It allows you to examine or modify the behavior of applications during execution.

Capabilities:

  • Discover class metadata (methods, fields, constructors, annotations)
  • Access private fields and methods
  • Create instances dynamically
  • Invoke methods dynamically
  • Modify field values at runtime

Use Cases:

  • Frameworks: Spring, Hibernate use reflection for dependency injection and ORM mapping
  • Testing: JUnit uses reflection to discover and invoke test methods
  • Serialization: Jackson, Gson use reflection to serialize/deserialize JSON

Understanding the Class Object

The java.lang.Class class is the entry point for reflection. Every loaded class has exactly one Class object that contains its metadata.

What Class Object Contains:

  • Class name, package, modifiers
  • Fields (member variables)
  • Methods (member functions)
  • Constructors
  • Annotations
  • Superclass and interfaces

Important: The JVM creates one Class object per loaded class, stored in the Method Area.

Obtaining Class Objects

There are three primary ways to obtain a Class object:

Method 1: Using .class Literal (Compile-time)

// Most efficient - no object instance needed

Class<?> userClass = User.class;

When to use: When you know the class name at compile time.

Method 2: Using getClass() Method (Runtime)

User user = new User("Deepak", "deepak@email.com");

Class<?> userClass = user.getClass();

When to use: When you have an object instance.

Method 3: Using Class.forName() (Dynamic Loading)

try {

// Loads the class if not already loaded

Class<?> userClass = Class.forName("com.vodafone.model.User");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

When to use: When class name is determined at runtime (e.g., from configuration files, database).

Complete Example:

Article content
Article content
Article content

Reflection on Constructors

  • Java Reflection lets you inspect constructors at runtime.
  • You can get public or private constructors, their parameters, and access modifiers.
  • Useful in frameworks, libraries, dependency injection, and testing.

Constructor<?>[] constructors = MyClass.class.getDeclaredConstructors();

Reflection on Fields

  • Allows runtime access to class variables (fields).
  • You can read or modify private fields by bypassing access checks.
  • Commonly used in ORMs (Hibernate), serializers, and debugging tools.

Field field = MyClass.class.getDeclaredField("name");

field.setAccessible(true);

Reflection on Methods

  • Enables discovering and invoking methods dynamically at runtime.
  • Can call private methods by changing accessibility.
  • Used in test frameworks (JUnit) and Spring internals.

Method method = MyClass.class.getDeclaredMethod("doWork");

method.setAccessible(true);

How to call a private constructor using Reflection?

Reflection allows bypassing Java access control using: constructor.setAccessible(true);

How to create an object using a private constructor?

class MyClass {

private MyClass() {

System.out.println("Private constructor called");

}

}

import java.lang.reflect.Constructor;

public class TestReflection {

public static void main(String[] args) throws Exception {

Class<MyClass> clazz = MyClass.class;

Constructor<MyClass> constructor =

clazz.getDeclaredConstructor();

constructor.setAccessible(true); // bypass private

MyClass obj = constructor.newInstance(); // object created

}

}

Important:

  • getDeclaredConstructor() → accesses private constructors
  • setAccessible(true) → breaks encapsulation
  • Used internally by Spring, Hibernate, Singleton breaking
  • Can be blocked by SecurityManager (older Java versions)

Why Reflection Should Be Used Carefully

  • Breaks OOP principles
  • Slower than normal calls
  • Can break Singleton pattern

Reflection gives power, not safety — use it only when really need it.

To view or add a comment, sign in

More articles by Deepak Singh

  • What is Lombok and why we need Lombok?

    🔹 What is Lombok and Why Do We Use It? Lombok is a powerful Java library and designed to reduce boilerplate code in…

  • GraphQL vs REST API — Explained with Real-Life Examples

    Fixed Response vs Flexible Response REST: Has a fixed response. GraphQL: Gives flexibility to consumers — they can…

  • Understanding Kubernetes Architecture: A Breakdown of Clusters, Nodes, Pods, and Containers

    Kubernetes is a powerful orchestration tool for managing containerized applications. To grasp its functionality, it's…

    1 Comment
  • What is GraphQL ?

    🧠 What is GraphQL? GraphQL is not just an API architectural style — It’s a powerful, flexible query language for APIs,…

    1 Comment
  • What is API ?

    🔌 Introduction to APIs An API (Application Programming Interface) is a set of rules that allows different software…

    6 Comments
  • Servlet and Servlet Container

    Servlet and Servlet container together provide the base for building web-based applications. Servlet is a Java class…

  • Transaction Management

    💡 What is a Transaction? Transactions are the backbone of any enterprise application. A transaction means a set of…

  • Understanding Java Records

    Introduction: In Java, records are a special type of class designed to minimize boilerplate code when creating data…

  • Sealed Class and Interface

    Sealed classes and interfaces control which other classes or interfaces can extend or implement them. This means you…

  • Key dependencies of Spring Boot

    spring-boot-starter-parent:Provides default configurations and dependency management. Use: In Maven, you include it as…

    2 Comments

Others also viewed

Explore content categories