Practical examples of Java Reflection API for beginners

If you’ve heard people mention Java reflection but it still feels a bit mysterious, you’re in the right place. In this guide, we’ll walk through practical, beginner‑friendly examples of Java Reflection API examples for beginners, and we’ll do it with real code you can actually run and modify. Instead of abstract theory, you’ll see how reflection behaves in everyday situations: inspecting classes, calling methods, changing fields, and even working with annotations. You’ll also see how these examples of Java Reflection API examples for beginners connect to real‑world Java frameworks you might already use or plan to learn, like dependency injection containers and testing libraries. Reflection can look intimidating at first, but once you see a clear example of how it works, it starts to feel more like a handy toolbox than black magic. By the end of this article, you’ll be able to read reflection‑based code with confidence and write simple reflective utilities of your own.
Written by
Taylor
Published

Starting with simple examples of Java Reflection API

Let’s skip the formal definitions and jump straight into simple, concrete examples of Java Reflection API behavior that beginners can understand.

Imagine a basic User class:

public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Reflection lets you inspect and work with this User class at runtime, even if you only know its name as a String.

Here is a very first example of using reflection to get basic class information:

public class ReflectionBasics {
    public static void main(String[] args) throws Exception {
        Class<?> userClass = Class.forName("com.example.User");

        System.out.println("Class name: " + userClass.getName());
        System.out.println("Simple name: " + userClass.getSimpleName());
        System.out.println("Package: " + userClass.getPackageName());
    }
}

This is one of the best examples of Java Reflection API for beginners because it shows the minimum moving parts: get a Class object, then ask it questions.


Inspecting fields and methods: examples include real output

Once you have a Class<?> object, you can list its fields and methods. These examples of Java Reflection API examples for beginners are great for building mental models.

Listing declared fields

Field[] fields = userClass.getDeclaredFields();
for (Field field : fields) {
    System.out.println(field.getName() + " : " + field.getType().getSimpleName());
}

For the User class, the output would look like:

name : String
age : int

Listing declared methods

Method[] methods = userClass.getDeclaredMethods();
for (Method method : methods) {
    System.out.println(method.getName());
}

You’ll see method names like getName, setName, getAge, setAge, and toString. This kind of listing is a classic example of reflection used in IDEs, documentation generators, and serialization libraries.

These are small, concrete examples of Java Reflection API behavior, but they mirror what big frameworks do under the hood.


Creating objects dynamically: a very common example of reflection

Sometimes you only know the class name at runtime (for example, from a config file or user input). Reflection lets you create an instance without hard‑coding the class.

String className = "com.example.User";

Class<?> userClass = Class.forName(className);
Object userInstance = userClass.getDeclaredConstructor().newInstance();

System.out.println(userInstance);

This example of using reflection to create objects is similar to what dependency injection containers (like Spring) have been doing for years. They read configuration, pick the class, and construct it with reflection.

In 2024–2025, this pattern still appears everywhere in Java ecosystems, especially in frameworks that manage your objects for you.


Accessing private fields: examples of Java Reflection API with setAccessible

Reflection can access private fields, which is powerful but should be used carefully.

User user = new User("Alice", 25);

Field nameField = User.class.getDeclaredField("name");
nameField.setAccessible(true); // WARNING: breaks normal encapsulation

System.out.println("Old name: " + nameField.get(user));
nameField.set(user, "Bob");
System.out.println("New name: " + nameField.get(user));

For beginners, this is one of the most eye‑opening examples of Java Reflection API examples for beginners because it shows that access modifiers can be bypassed at runtime.

In modern Java (17+), reflection with setAccessible(true) is more restricted by the module system. Many libraries now use method handles and well‑defined module exports, but reflection is still widely used, especially in testing.


Invoking methods dynamically: another best example for beginners

Let’s say you want to call setName and getName using reflection.

User user = new User("Alice", 25);

Method setNameMethod = User.class.getMethod("setName", String.class);
setNameMethod.invoke(user, "Charlie");

Method getNameMethod = User.class.getMethod("getName");
Object result = getNameMethod.invoke(user);

System.out.println("Name via reflection: " + result);

This example of reflective method invocation is very close to what JSON mappers and ORMs do: they inspect your class, find getters and setters, and call them at runtime.

If you’re looking for real examples of Java Reflection API examples for beginners that connect directly to real‑world frameworks, this is it.


Working with constructors: examples include parameterized constructors

Reflection can also work with constructors that have parameters.

Constructor<User> ctor = User.class.getConstructor(String.class, int.class);
User user = ctor.newInstance("Dana", 30);

System.out.println(user);

This gives you a new User with the specified name and age. You can imagine a configuration file like:

{
  "class": "com.example.User",
  "args": ["Evan", 28]
}

A small framework could read that JSON, then use reflection to pick the right constructor and create the instance. These are practical examples of Java Reflection API examples for beginners that feel very close to real production scenarios.


Reading annotations with reflection: modern 2024–2025 style usage

Annotations are everywhere in modern Java: Spring, Jakarta EE, JUnit 5, and more. Reflection is what makes annotations useful.

Consider a simple custom annotation and a class that uses it:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface JsonField {
    String value();
}
public class Product {
    @JsonField("product_name")
    private String name;

    @JsonField("price_usd")
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

Now use reflection to read those annotations and build a Map that looks like JSON:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class JsonSerializer {

    public static Map<String, Object> toJsonMap(Object obj) throws IllegalAccessException {
        Map<String, Object> result = new HashMap<>();
        Class<?> clazz = obj.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            JsonField annotation = field.getAnnotation(JsonField.class);
            if (annotation != null) {
                field.setAccessible(true);
                String jsonKey = annotation.value();
                Object value = field.get(obj);
                result.put(jsonKey, value);
            }
        }
        return result;
    }
}

Usage:

public class Main {
    public static void main(String[] args) throws IllegalAccessException {
        Product product = new Product("Laptop", 1299.99);
        Map<String, Object> jsonMap = JsonSerializer.toJsonMap(product);
        System.out.println(jsonMap);
    }
}

Output might look like:

{product_name=Laptop, price_usd=1299.99}

This is one of the best examples of Java Reflection API examples for beginners because it shows a mini‑version of what libraries like Jackson or Gson do in real applications.


Reflection in testing: real examples with JUnit‑style utilities

In testing, reflection is often used to inspect or modify internal state when you don’t want to change the production code just for tests.

Here is a small utility that sets a private field value for testing:

public class TestUtils {

    public static void setPrivateField(Object target, String fieldName, Object value) {
        try {
            Field field = target.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(target, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

Usage in a test:

public class UserServiceTest {

    @org.junit.jupiter.api.Test
    void testWithPrivateField() {
        User user = new User("Temp", 0);

        TestUtils.setPrivateField(user, "age", 42);

        assert user.getAge() == 42;
    }
}

Frameworks like JUnit and Mockito use reflection heavily. When you see @Test or @Mock, reflection is usually involved. These are solid, real examples of Java Reflection API examples for beginners who want to understand what their tools are secretly doing.


Performance and safety in 2024–2025: how reflection fits today

Reflection is powerful, but it comes with trade‑offs.

Performance:

Reflection can be slower than direct method calls because the JVM can’t optimize reflective calls as aggressively. For performance‑sensitive code, the recommended approach is to:

  • Use reflection once to discover methods or fields.
  • Cache Method, Field, or Constructor references.
  • Reuse them instead of doing repeated lookups.

Security and modules:

Modern Java (9 and later) introduced the module system. Calls like setAccessible(true) may fail if modules are locked down. Many frameworks now use a mix of reflection and method handles, or they require explicit --add-opens options when you start the JVM.

For a deeper background on Java security and reflection‑related concerns, you can explore the general secure coding guidance from the U.S. Cybersecurity & Infrastructure Security Agency at cisa.gov and software assurance resources from nist.gov.

The main idea for beginners: use these examples of Java Reflection API examples for beginners to learn how things work, but be thoughtful about using reflection in performance‑critical or security‑sensitive code.


Putting it together: a mini plugin loader using reflection

To pull several ideas together, here is a small, higher‑level example of reflection that feels like a real application feature.

Define a simple plugin interface:

public interface Plugin {
    void run();
}

Create two implementations:

public class HelloPlugin implements Plugin {
    @Override
    public void run() {
        System.out.println("Hello from HelloPlugin");
    }
}

public class GoodbyePlugin implements Plugin {
    @Override
    public void run() {
        System.out.println("Goodbye from GoodbyePlugin");
    }
}

Now write a tiny plugin loader that uses reflection and a list of class names (maybe from a config file):

import java.util.List;

public class PluginRunner {

    public static void main(String[] args) throws Exception {
        List<String> pluginClassNames = List.of(
                "com.example.HelloPlugin",
                "com.example.GoodbyePlugin"
        );

        for (String className : pluginClassNames) {
            Class<?> clazz = Class.forName(className);

            if (!Plugin.class.isAssignableFrom(clazz)) {
                System.out.println(className + " does not implement Plugin");
                continue;
            }

            Plugin plugin = (Plugin) clazz.getDeclaredConstructor().newInstance();
            plugin.run();
        }
    }
}

This small plugin system is one of the best examples of Java Reflection API examples for beginners who want to see how reflection enables flexible, configurable architectures. In 2024–2025, many real systems still use this basic pattern to load optional modules, user extensions, or integration adapters.

If you want to go further with language and runtime concepts in a more academic way, many universities publish Java and reflection material; for instance, you can browse programming language course notes from sites like mit.edu or stanford.edu for deeper background on runtime behavior.


FAQ: short answers with reflection examples

Q: Can you give a simple example of Java reflection to inspect a class?
Yes. The shortest example of class inspection looks like this:

Class<?> clazz = String.class;
System.out.println(clazz.getName());
for (Method m : clazz.getDeclaredMethods()) {
    System.out.println(m.getName());
}

This prints the class name and all declared methods.

Q: What are some real examples of Java Reflection API usage in popular frameworks?
Real examples include scanning for annotations like @Controller or @Entity, creating objects for dependency injection, mapping JSON fields to Java fields, and running test methods marked with @Test in JUnit.

Q: Is reflection safe for beginners to use in production code?
It’s safe if you understand the trade‑offs. Reflection can break encapsulation, ignore access modifiers, and cause runtime errors if class or method names change. For most everyday business logic, prefer normal method calls and constructors. Use reflection when you truly need flexibility, and keep the reflective code well‑tested.

Q: Does reflection still matter with modern Java versions and frameworks in 2024–2025?
Yes. Even with newer approaches like method handles and ahead‑of‑time compilation, reflection is still deeply embedded in major frameworks. Learning from these examples of Java Reflection API examples for beginners will help you read and understand framework internals, configuration behavior, and advanced libraries.

Q: How can I practice with more examples of reflection without breaking my project?
Create a small sandbox project just for experiments. Re‑implement simple features like a mini JSON mapper, a tiny plugin loader, or a test utility that sets private fields. Treat these as practice exercises so you can explore different examples of Java Reflection API examples for beginners without risking production code.

Explore More Java Code Snippets

Discover more examples and insights in this category.

View All Java Code Snippets