Core Java

How to Retrieve String Fields with Java Reflection

Java Reflection enables runtime inspection and modification of classes, fields, methods, and constructors. This capability is often used in frameworks, libraries, and tools where compile-time knowledge of classes is not always available. In this article, we will learn how to retrieve the value of a String field from a Java object using reflection.

1. Creating the Model Class

We begin by defining a simple class with one public field and one private field. This setup allows us to see the difference between reflective access for the two cases.

public class Person {

    public String firstName;    // public field
    private String lastName;    // private field

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

The Person class has two fields: firstName (accessible directly without reflection) and lastName (requires reflection to access). We will demonstrate retrieving both using reflection.

2. Accessing a Public Field via Reflection

When a field is declared public, it can be accessed using reflection with the getField() method. Since the field is already accessible, we do not need to call setAccessible(true).

public class PublicFieldAccess {

    public static String getPublicFieldValue(Object target, String fieldName) {
        try {
            // Retrieve the public field (works only for public fields)
            Field field = target.getClass().getField(fieldName);

            // Directly read its value (no setAccessible required)
            Object value = field.get(target);
            return (String) value;

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Public field not found: " + fieldName, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Cannot access public field: " + fieldName, e);
        }
    }
}

The getField() method looks up only public fields, including those inherited from superclasses. This method cannot access private fields. In our case, it works fine for firstName, which is explicitly declared as public.

3. Accessing a Private Field via Reflection

When a field is private, the JVM prevents direct reflective access. To override this, we use getDeclaredField() and then call setAccessible(true).

public class PrivateFieldAccess {

    public static String getPrivateFieldValue(Object target, String fieldName) {
        try {
            // Retrieve the declared field (includes private ones)
            Field field = target.getClass().getDeclaredField(fieldName);

            // Override Java access checks
            field.setAccessible(true);

            // Read its value
            Object value = field.get(target);
            return (String) value;

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Private field not found: " + fieldName, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Cannot access private field: " + fieldName, e);
        }
    }
}

The getDeclaredField() method allows us to access both public and non-public fields defined in the class itself. Calling setAccessible(true) disables Java’s access checks, enabling us to read or write private values. Without this, an IllegalAccessException would be thrown.

4. Generic Reflection Utility for Any String Field

To make our code reusable, we can also create a generic utility method that retrieves any String field (whether public or private).

public class ReflectionUtil {

    public static String getStringFieldValue(Object target, String fieldName) {
        try {
            // Try to get the declared field (works for private & public)
            Field field = target.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);

            // Get and cast the value
            Object value = field.get(target);
            return (String) value;

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Field not found: " + fieldName, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Cannot access field: " + fieldName, e);
        } catch (ClassCastException e) {
            throw new RuntimeException("Field " + fieldName + " is not a String", e);
        }
    }
}

Unlike PublicFieldAccess and PrivateFieldAccess, this method doesn’t distinguish between access levels. It directly uses getDeclaredField() and setAccessible(true), making it suitable for any String field. This is useful in scenarios where we don’t know in advance whether a field is public or private.

Demonstrating All Approaches in Main

Let’s put everything together in a main method class that tests each of the three approaches.

public class ReflectString {

    public static void main(String[] args) {
        // Create a Person object
        Person person = new Person("Tom-Public", "Tom-Private");

        // Access public field
        String publicName = PublicFieldAccess.getPublicFieldValue(person, "firstName");
        System.out.println("Public field value: " + publicName);

        // Access private field
        String privateName = PrivateFieldAccess.getPrivateFieldValue(person, "lastName");
        System.out.println("Private field value: " + privateName);

        // Use generic utility
        String nameViaGeneric = ReflectionUtil.getStringFieldValue(person, "lastName");
        System.out.println("Private field via generic utility: " + nameViaGeneric);
    }
}

The MainApp class creates a Person object and retrieves values in three different ways:

  • Using PublicFieldAccess to get firstName.
  • Using PrivateFieldAccess to get lastName.
  • Using ReflectionUtil to get lastName generically.

When the application runs, the output will be:

Public field value: Tom-Public
Private field value: Tom-Private
Private field via generic utility: Tom-Private

This confirms that reflection can access both public and private fields, although the approach differs depending on the field’s visibility.

5. Conclusion

This article demonstrated how to use reflection to retrieve String field values from Java objects. While reflection is a powerful capability, it must be applied cautiously since it can break encapsulation, impact performance, and pose security risks. In typical application code, standard getters are the preferred approach, reserving reflection for cases like frameworks, libraries, or tools that require runtime introspection.

6. Download the Source Code

This article explored how to use Java Reflection to retrieve the value of a String field.

Download
You can download the full source code of this example here: Java reflection string value field

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button