🕌
MapからRecordへの変換
これは何ですか?
Java 16で採用されたRecordを生成します。
Mapに同じ名前で設定しておいて変換します。
ソースコード
public static <R extends Record> R Map2Record(Class<R> cls, Map<String, Object> map) throws ReflectiveOperationException {
RecordComponent[] rc = cls.getRecordComponents();
Class<?>[] types = new Class<?>[rc.length];
Object[] args = new Object[rc.length];
for (int i = 0; i < rc.length; i++) {
types[i] = rc[i].getType();
args[i] = map.get(rc[i].getName());
}
return cls.getDeclaredConstructor(types).newInstance(args);
}
使用例
public record Account(String username, String domain, int count) {}
Map<String, Object> map = new HashMap<>();
map.put("username", "foo");
map.put("domain", "example.com");
map.put("count", 1);
try {
Account account = Map2Record(Account.class, map);
System.out.println(account);
} catch (ReflectiveOperationException ex) {
}
=> Account[username=foo, domain=example.com, count=1]
Discussion