← 中文资源

简体中文版本

Record Components 反射

通过 getRecordComponents 检查 record 的组件,反射调用每个访问器,并累加组件返回的值。

阅读英文原文

实现说明

全部逻辑都在类 Main、Point中。 本示例的循环部分是 for (RecordComponent component : components)。

使用要点

  • 跑完文件,输出里会留下标记——is record:、component count:、sum:。

常见问题

运行「Record Components 反射」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 is record:、component count:、sum: 标签标明各步骤。

核心语句

sum += (Integer) value;

代码示例

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());
    }
}