import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class BeanToMapExample {
public static Map<String, Object> convertBeanToMap(Object bean) {
Map<String, Object> map = new HashMap<>();
try {
// 获取类的Bean信息
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : propertyDescriptors) {
String propertyName = descriptor.getName();
// 获取getter方法
Method getterMethod = descriptor.getReadMethod();
if (getterMethod != null) {
// 调用getter方法获取属性值
Object propertyValue = getterMethod.invoke(bean);
map.put(propertyName, propertyValue);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
// 示例Java Bean
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Person person = new Person();
person.setName("John");
person.setAge(30);
// 将Java Bean转换为Map
Map<String, Object> personMap = convertBeanToMap(person);
System.out.println(personMap); // 输出: {name=John, age=30, class=class BeanToMapExample$1Person}
}
}
convertBeanToMap 方法:
Map<String, Object>。Introspector.getBeanInfo()获取Bean的所有属性描述符(PropertyDescriptor),然后通过反射调用每个属性的getter方法,将属性名和属性值存入Map中。示例代码:
Person类,包含两个属性:name和age。Person对象并设置其属性值。convertBeanToMap方法将Person对象转换为Map,并打印结果。注意事项:
Introspector.getBeanInfo()会返回所有继承自Object类的方法,因此Map中会包含一个名为class的键,其值为对象的类类型。如果不需要这个键,可以在循环中过滤掉它。上一篇:java https请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站