您可以使用以下方法:
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));
}
}