Java Reflection API Examples for Beginners

Explore practical examples of Java Reflection API to enhance your programming skills.
By Jamie

Introduction to Java Reflection API

The Java Reflection API is a powerful tool that allows developers to inspect and manipulate classes, methods, and fields at runtime. This capability can be particularly useful for various applications such as debugging, testing, and dynamic object manipulation. Below are three practical examples demonstrating different use cases of the Java Reflection API.

Example 1: Accessing Private Fields

In this example, we will access a private field of a class using reflection. This can be useful in scenarios where you need to test or modify the internal state of an object without changing its access modifiers.

First, consider a simple class with a private field:

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }
}

Now, we can use reflection to access and modify the private field ’name’:

import java.lang.reflect.Field;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        Person person = new Person("John");
        Field field = Person.class.getDeclaredField("name");
        field.setAccessible(true); // Bypass the private access
        String name = (String) field.get(person);
        System.out.println("Before: " + name); // Output: John

        field.set(person, "Jane");
        name = (String) field.get(person);
        System.out.println("After: " + name); // Output: Jane
    }
}

Notes:

  • Using setAccessible(true) allows access to private fields, but should be used cautiously due to security implications.

Example 2: Invoking Methods Dynamically

This example demonstrates how to invoke a method dynamically at runtime using reflection. This is particularly useful when the method to be called is not known at compile time.

Consider a class with a method that performs a simple calculation:

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

We can invoke the ‘add’ method dynamically as follows:

import java.lang.reflect.Method;

public class ReflectionMethodExample {
    public static void main(String[] args) throws Exception {
        Calculator calculator = new Calculator();
        Method method = Calculator.class.getMethod("add", int.class, int.class);
        int result = (int) method.invoke(calculator, 5, 10);
        System.out.println("Result: " + result); // Output: Result: 15
    }
}

Notes:

  • getMethod is used to retrieve public methods. Use getDeclaredMethod to access private methods.

Example 3: Creating Instances Dynamically

In this example, we will demonstrate how to create an instance of a class dynamically using the Reflection API. This is useful in frameworks or libraries that require creating objects without knowing their concrete types at compile time.

Consider a class with a constructor:

class Car {
    private String model;

    public Car(String model) {
        this.model = model;
    }
}

We can create an instance of ‘Car’ dynamically:

import java.lang.reflect.Constructor;

public class ReflectionInstanceExample {
    public static void main(String[] args) throws Exception {
        Class<?> carClass = Car.class;
        Constructor<?> constructor = carClass.getConstructor(String.class);
        Car car = (Car) constructor.newInstance("Toyota");
        System.out.println("Car model: " + car.model); // Accessing private field directly is not possible
    }
}

Notes:

  • To access private fields, you would need to use reflection as shown in the first example.

These examples illustrate the versatility of the Java Reflection API, making it a valuable tool for developers looking to enhance their applications.