java中使用反射将javaBean转为map
key : 字段名称
value: 字段值
package test.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
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;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartUpApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PersontTest {
@Test
public void test1() throws Exception {
Person person = new Person();
person.setAge(22);
person.setName("jk");
System.out.println(person);
Map<String, Object> map = beanToMap(person);
System.out.println(map);
}
//JavaBean转换为Map
public static Map<String, Object> beanToMap(Object bean) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> cl = bean.getClass();
//获取指定类的BeanInfo 对象
BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
//获取所有的属性描述器
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String key = pd.getName();
Method getter = pd.getReadMethod();
Object value = getter.invoke(bean);
map.put(key, value);
}
return map;
}
}