Javaでオブジェクトをマップに変換する方法は何ですか?
JavaでObjectをMapに変換する方法には次のようなものがあります:
- Javaのリフレクション機構を使用して、Objectのすべてのフィールドを取得し、フィールド名をキー、フィールド値を値としてMapに格納します。
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
- JavaBeanのgetメソッドを使用する:JavaBeanのgetメソッドを使ってObjectのプロパティ値を取得し、プロパティ名をキー、プロパティ値を値としてMapに保存します。
public static Map<String, Object> objectToMap(Object obj) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
if (!key.equals("class")) {
Method getter = propertyDescriptor.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
return map;
}
- 第三者のライブラリ、たとえばApache Commons BeanUtilsやSpringのBeanUtilsを使用してください。これらのライブラリは、ObjectをMapに変換するためのより簡単な方法を提供しています。
Apache Commons BeanUtilsを使用する:
import org.apache.commons.beanutils.BeanUtils;
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, Object> map = new HashMap<>();
map = BeanUtils.describe(obj);
map.remove("class");
return map;
}
SpringのBeanUtilsを使用する:
import org.springframework.beans.BeanUtils;
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
BeanUtils.copyProperties(obj, map);
return map;
}