Record Components Reflection
Inspect a record through getRecordComponents, invoke each accessor reflectively, and sum the values returned by the components.
Code
import java.lang.reflect.RecordComponent;
public class Main {
record Point(int x, int y) {
}
public static void main(String[] args) throws Exception {
System.out.println("is record: " + Point.class.isRecord());
// reflection exposes the canonical components in order
RecordComponent[] components = Point.class.getRecordComponents();
System.out.println("component count: " + components.length);
Point point = new Point(3, 4);
int sum = 0;
for (RecordComponent component : components) {
// the accessor is the method with the component name
Object value = component.getAccessor().invoke(point);
System.out.println(component.getName() + ": " + component.getType().getSimpleName()
+ " = " + value);
sum += (Integer) value;
}
System.out.println("sum: " + sum);
// the canonical constructor order matches the component order
System.out.println("first declared: " + components[0].getName());
}
}How it works
The working surface is the classes Main and Point — everything else is wiring.
One loop does the cycling here: for (RecordComponent component : components).
Points of care
- The only prerequisite is the language toolchain itself.
Applying it
The file announces its steps in the output: is record:, component count:, sum:.
Statements that matter
sum += (Integer) value;
Interactive Tools for This Topic
FAQ
- What does Record Components Reflection print when run?
- Run it as a complete program — the output lines carry labels such as `is record:`, `component count:`, `sum:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.