Object 转为map
时间: 2023-09-06 18:13:38 浏览: 90
您可以使用Java中的BeanUtils工具类将Java对象转换为Map类型。下面是示例代码:
```
import org.apache.commons.beanutils.BeanUtils;
// Java对象
public class Person {
private String name;
private int age;
// 省略getter和setter方法
}
// 将Java对象转换为Map
public static Map<String, String> objectToMap(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
BeanUtils.populate(map, obj);
return map;
}
// 测试代码
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Map<String, String> map = objectToMap(person);
System.out.println(map); // 输出: {age=20, name=Tom}
}
```
阅读全文