5

我有一堂课:

class A {
   public final Integer orgId;
}

我将其替换为 Java 17 中的记录:

record A (Integer orgId) {
}

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

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

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

4

2 回答 2

8

您可以使用以下方法:

RecordComponent[] getRecordComponents()

您可以从RecordComponent.

点.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));
    }
}
于 2021-10-13T11:01:05.943 回答
0

你的classrecord不等价:记录有私有字段。

Class#getFields()仅返回公共字段。

你可以Class#getDeclaredFields()改用。

于 2021-10-13T10:58:39.573 回答