如何通过反射在 Java 17 中获取所有 Record 字段及其值?

How do I get all Record fields and its values via reflection in Java 17?

我有一个 class:

class A {
   public final Integer orgId;
}

我用Java17:

中的记录替换了
record A (Integer orgId) {
}

此外,我有一个代码通过反射进行验证,它与常规 class 一起使用,但不适用于记录:

Field[] fields = obj.getClass().getFields(); //getting empty array here for the record
for (Field field : fields) {
}

在 Java17 中通过反射获取 Record 对象字段及其值的正确方法是什么?

您的 classrecord 不等同:记录有 private 字段。

Class#getFields() returns public 字段。

您可以改用 Class#getDeclaredFields()

您可以使用以下方法:

RecordComponent[] getRecordComponents()

您可以从 RecordComponent.

中检索名称、类型、泛型类型、注释及其访问器方法

Point.java:

record Point(int x, int y) { }

RecordDemo.java:

import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class RecordDemo {
    public static void main(String args[]) throws InvocationTargetException, IllegalAccessException {
        Point point = new Point(10,20);
        RecordComponent[] rc = Point.class.getRecordComponents();
        System.out.println(rc[0].getAccessor().invoke(point));
    }
}

输出:

10

或者,

import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;

public class RecordDemo {
    public static void main(String args[]) 
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
        Point point = new Point(10, 20);
        RecordComponent[] rc = Point.class.getRecordComponents();      
        Field field = Point.class.getDeclaredField(rc[0].getAccessor().getName());  
        field.setAccessible(true); 
        System.out.println(field.get(point));
    }
}