Set object property using reflection
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Reflection lets you inspect and modify objects at runtime when compile-time types are not enough. It is useful in frameworks, generic mappers, test tooling, and admin utilities where field names or property names arrive as data. The key is to use reflection in a controlled way so dynamic behavior does not reduce safety and maintainability.
When Reflection Is the Right Tool
Most application code should use normal method calls. Reflection becomes valuable when you need one reusable component that can work with many unrelated classes, such as a CSV importer, configuration binder, or generic patch endpoint. In these cases, hard-coding setter calls for every model becomes expensive and brittle.
Before implementing reflection-based mutation, define clear rules:
- Which fields are allowed to change.
- What input types are accepted.
- How conversion errors are reported.
- Whether private members are allowed.
These rules prevent dangerous behavior where arbitrary input can mutate sensitive fields.
Field-Based Property Updates in Java
The direct approach uses java.lang.reflect.Field. You find a field by name, make it accessible, convert the incoming value to the correct type, and assign it.
This code is runnable and intentionally strict. Unsupported types fail fast, which is usually better than silent coercion.
Setter-Based Updates for Better Encapsulation
Direct field mutation bypasses business rules that may exist inside setters. If your domain classes validate state in setter methods, invoke methods rather than fields. This keeps validation logic active and reduces invalid object states.
A common production pattern is to keep a whitelist of allowed properties, then call setBySetter only for those names.
Performance and Reliability Considerations
Reflection is slower than direct calls, but in many request flows the overhead is acceptable. If profiling shows reflection hot spots, cache field and method lookups in a map keyed by class and property name. Caching removes repeated metadata scanning and often provides most of the needed gain.
Reliability is usually a bigger concern than raw speed. Add strong error messages with property name, target class, and expected type. That makes bad input easy to diagnose.
In frameworks and APIs, wrap reflection errors in application-level exceptions. A generic stack trace from IllegalArgumentException is not enough for clients and support teams.
Common Pitfalls
- Mutating private fields that should stay controlled. Prefer setters when domain validation exists.
- Skipping type conversion rules. Always convert deliberately and reject unknown conversions.
- Allowing any property name from user input. Use a whitelist to prevent unintended updates.
- Ignoring inherited fields. Search the class hierarchy when field access is required.
- Repeating reflection lookup in hot loops. Cache metadata when performance matters.
Summary
- Reflection is powerful for generic mappers and runtime-driven property updates.
- Field-based mutation is simple but can bypass business validation.
- Setter-based mutation better preserves encapsulation and invariants.
- Explicit conversion, clear errors, and property whitelists make reflection safe in production.
- Cache metadata only after you confirm performance pressure with profiling.
Related reading
- Setting a log file name to include current date in Log4j
- Setting active profile and config location from command line in Spring Boot
- Setting active profile and config location from command line in Spring Boot
- Setting default values for columns in JPA
- Setting Precedence of Multiple ControllerAdvice ExceptionHandlers
- Setting Short Value Java
- Setting Spring Profile variable
- Setting the default active profile in Spring-boot

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.