← All Exercises

Java Reflection Field Access

advancedjava~30min

Background

Reflection enables runtime class inspection and manipulation, used in frameworks like Spring and Hibernate.

Problem

Write a Java method that uses reflection to copy all field values from one object to another of the same class.

Input

Two objects of the same class: source and target.

Output

The target object with all fields copied from the source.

Sample tests

Sample 1

Input: source={a:1,b:2}, target={a:0,b:0}
Expected: target={a:1,b:2}

Your solution

Learning objective

Learn reflection field access, setAccessible for private fields, and the performance implications.