java对象转map代码示例
时间: 2024-05-25 12:08:44 浏览: 110
JSONArrayToMap.txt
Java对象转Map可以通过Java反射机制来实现,以下是一个示例代码:
```
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ObjectToMapDemo {
public static void main(String[] args) {
Person person = new Person("张三", 20);
Map<String, Object> map = objectToMap(person);
System.out.println(map);
}
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
map.put(field.getName(), field.get(obj));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
}
```
阅读全文