Understanding Java Reflection: Concepts, Usage, and Practical Applications

This article explains the core ideas of Java reflection, demonstrates how to obtain Class objects, create instances, access fields and methods, and discusses common use cases such as Spring IoC, factory patterns, and JDBC driver loading, while also covering its advantages, drawbacks, and best‑practice tips.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Understanding Java Reflection: Concepts, Usage, and Practical Applications

Reflection Concept and Role

Reflection is a crucial technique in Java that allows a program to inspect and manipulate classes, fields, methods, and constructors at runtime, enabling dynamic behavior such as choosing implementations based on configuration.

Basic Usage of Reflection

The main components of Java reflection are Class, Field, Constructor, and Method. Each provides APIs to retrieve metadata and perform operations.

Obtaining a Class Object

ClassName.class

– works when the class is known at compile time. instance.getClass() – obtains the Class from an existing object. Class.forName("full.class.Name") – loads the class by its fully‑qualified name at runtime.

Class clazz = SmallPineapple.class;
SmallPineapple sp = new SmallPineapple();
Class clazz = sp.getClass();
Class clazz = Class.forName("com.bean.SmallPineapple");

Creating Instances

clazz.newInstance()

– invokes the default no‑arg constructor.

Using Constructor to call a specific constructor with parameters.

Class clazz = Class.forName("com.bean.SmallPineapple");
SmallPineapple obj = (SmallPineapple) clazz.newInstance();
Constructor ctor = clazz.getConstructor(String.class, int.class);
SmallPineapple obj2 = (SmallPineapple) ctor.newInstance("小菠萝", 21);

Invoking Methods

After obtaining a Method object, call invoke with the target instance (or null for static methods).

Method method = clazz.getMethod("getInfo");
method.invoke(obj2);

Common Application Scenarios

Spring IoC Container : Spring reads applicationContext.xml, creates bean instances via reflection, and stores them in the IoC container.

Reflection + Factory Pattern : A factory can instantiate any subclass by passing its class name, eliminating hard‑coded branches.

JDBC Driver Loading : The driver class is loaded with Class.forName(driverClass), allowing the database type to be changed via configuration without code changes.

Spring IoC Example

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SmallPineapple bean = (SmallPineapple) ac.getBean("smallpineapple");
bean.getInfo();

Factory Using Reflection

public class MapFactory {
    public Map<Object,Object> produceMap(String className) throws Exception {
        Class clazz = Class.forName(className);
        return (Map<Object,Object>) clazz.newInstance();
    }
}

Advantages and Drawbacks of Reflection

Flexibility : Enables dynamic object creation and reduces code changes when requirements evolve.

Encapsulation Breakage : Private members can be accessed via setAccessible(true), violating encapsulation.

Performance Overhead : Reflection involves additional checks and cannot be fully optimized by the JVM; the impact is noticeable only after a large number of calls.

Flexibility Example

Changing the data source in a Spring Boot application is as simple as updating spring.datasource.type in application.yml without modifying any Java code.

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

Encapsulation Violation Example

SmallPineapple sp = new SmallPineapple("小菠萝", 21, 54.5);
Field weight = sp.getClass().getDeclaredField("weight");
weight.setAccessible(true);
System.out.println("Weight: " + weight.get(sp));

Performance Note

For a few or dozens of reflective calls the overhead is negligible; however, in hot loops with millions of calls, the cost becomes significant, so avoid reflection in performance‑critical paths.

Conclusion

Reflection acts like a mirror that reveals class information at runtime.

It enables dynamic instantiation, making programs more robust against changing requirements.

Typical scenarios include Spring IoC, factory patterns, and JDBC driver loading.

Key characteristics: increased flexibility, potential encapsulation breach, and performance cost.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaReflectionspringJDBCFactory Pattern
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.