Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Concepts and Practical Implementation of Java Reflection Mechanism

Tech 1

Java reflection enables programs to inspect, acces, and modify structural information of classes, methods, fields, and constructors during runtime, rather than requiring all type information to be known at compile time. This capability enables highly flexible dynamic programming logic, and all supporting interfaces and classes are provided under the java.lang.reflect package.

Obtaining Class Objects

All reflection operations start with a Class object, which represents the type metadata of a target class. There are three standard ways to fetch this object:

  1. Access the static .class attribute directly from the target type, e.g. Person.class
  2. Call the Class.forName(String fullyQualifiedClassName) static method, which is commonly used for dynamically loading classes by their full path
  3. Invoke the getClass() method on an existing instance of the target class, inherited from java.lang.Object

Fetching Class Metadata

The Class class exposes a set of utility methods to retrieve full metadata of the target type, including but not limited to:

  • Class full name and simple name
  • Belonging package information
  • Inherited parent class
  • All implemented interfaces
  • Public and all declared constructors
  • Public and all declared methods
  • Public and all declared member fields

For example, calling getMethods() returns an array of all public methods defined in the class and inherited from parent classes, while getDeclaredMethods() returns all methods declared directly in the class regardless of access modifier.

Dynamic Object Instantiation

You can create instances of the target class dynamically via the Class object or its associated Constructor objects:

  1. Call newInstance() directly on the Class object (note this method is deprecated as of Java 9, as it only works with no-arg constructors and wraps checked exceptions improperly)
Class<?> personCls = Person.class;
Person defaultPerson = (Person) personCls.newInstance();
  1. Fetch a matching Constructor instance first, then call its newInstance() method to pass constructor parameters, which is the recommended approach for all Java versions:
Constructor<?> paramConstructor = personCls.getConstructor(String.class);
Object personInstance = paramConstructor.newInstance("Alice Miller");

Dynamic Method Invocation

The Method class provides the invoke() method to call the corresponding method on a target instance. You can fetch a Method object via getMethod() (for public methods) or getDeclaredMethod() (for any declared method):

Method greetMethod = personCls.getMethod("greet");
// Invoke the greet method on the personInstance object
greetMethod.invoke(personInstance);

For non-public methods, you need to call setAccessible(true) on the Method instance first to bypass access control checks.

Field Access and Modification

The Field class supports reading and writing the value of a corresponding field on a target instance:

Field fullNameField = personCls.getDeclaredField("fullName");
// Bypass access check for private field
fullNameField.setAccessible(true);
// Update the fullName value of personInstance to "Bob Carter"
fullNameField.set(personInstance, "Bob Carter");
// Read the current value of the field
String currentName = (String) fullNameField.get(personInstance);

Performance and Security Notes

Reflection operations introduce additional runtime type resolution overhead, so they typically execute slower than equivalent direct static calls. Additionally, the ability to bypass access control checks can break encapsulation and introduce security vulnerabilities if used improperly, so reflection should only be used when no static implementation alternative is available.

Complete Working Example

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

class Person {
    private String fullName;

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

    public void greet() {
        System.out.printf("Greetings, my name is %s%n", fullName);
    }
}

public class ReflectionTest {
    public static void main(String[] args) throws Exception {
        // Obtain Class object for Person type
        Class<?> personCls = Person.class;

        // Print class metadata
        System.out.println("Target class full name: " + personCls.getName());

        // Create instance via parameterized constructor
        Constructor<?> constructor = personCls.getConstructor(String.class);
        Object personInstance = constructor.newInstance("Alice Miller");

        // Invoke public greet method
        Method greetMethod = personCls.getMethod("greet");
        greetMethod.invoke(personInstance);

        // Modify private fullName field
        Field nameField = personCls.getDeclaredField("fullName");
        nameField.setAccessible(true);
        nameField.set(personInstance, "Bob Carter");

        // Verify field modification
        greetMethod.invoke(personInstance);
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.