我有一節課:
class A {
public final Integer orgId;
}
我用 Java 17 中的記錄替換了它:
record A (Integer orgId) {
}
此外,我有一個通過反射進行驗證的代碼,該代碼與常規類一起作業,但不適用于 Records:
Field[] fields = obj.getClass().getFields(); //getting empty array here for the record
for (Field field : fields) {
}
在 Java 17 中通過反射獲取 Record 物件欄位及其值的正確方法是什么?
uj5u.com熱心網友回復:
您可以使用以下方法:
RecordComponent[] getRecordComponents()
您可以從 中檢索名稱、型別、泛型型別、注釋及其訪問器方法RecordComponent。
點.java:
record Point(int x, int y) { }
記錄演示.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));
}
}
uj5u.com熱心網友回復:
您的class和record不等價:記錄具有私有欄位。
Class#getFields()僅回傳公共欄位。
你可以用Class#getDeclaredFields()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311588.html
