在和外部系统对接时,对方系统提供的SDK方法入参全是Map,没办法,只能想办法把对象转成Map。这里,借助了hutool的工具类,可以方便的通过反射获取对象的属性。引入hutool的maven配置:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
工具类代码如下:
import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class BeanConvertUtils {
public static Map<String, String> beanToMap(Object bean) {
Map<String, String> targetMap = new HashMap<>();
if (bean == null) {
return null;
}
//获取类的属性描述
final Collection<BeanDesc.PropDesc> props = BeanUtil.getBeanDesc(bean.getClass()).getProps();
String key;
Method getter;
Object value;
for (BeanDesc.PropDesc prop : props) {
key = prop.getFieldName();
// 过滤class属性
// 得到property对应的getter方法
getter = prop.getGetter();
if (null != getter) {
// 只读取有getter方法的属性
try {
value = getter.invoke(bean);
} catch (Exception ignore) {
continue;
}
//如果是集合特殊处理
if (value != null && value instanceof Collection) {
listToMap(targetMap, (Collection<Object>) value, key);
continue;
}
if (value != null && false == value.equals(bean)) {
targetMap.put(key, null == value ? null : String.valueOf(value));
}
}
}
return targetMap;
}
private static Map<String, String> listToMap(Map<String, String> targetMap, Collection<Object> collection, String fieldName) {
int i = 0;
for (Object bean : collection) {
Map<String, String> tempMap = beanToMap(bean);
for (String key : tempMap.keySet()) {
targetMap.put(fieldName + "[" + i + "]." + key, tempMap.get(key));
}
i++;
}
return targetMap;
}
}
写一个测试类,测试一下:
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class BeanConvertUtilsTest {
@Test
public void beanToMapTest() {
Student student = new Student();
student.setNumber("2023120121");
student.setName("李磊");
Course course = new Course();
course.setName("语文");
course.setScore("90");
student.addCourse(course);
course = new Course();
course.setName("数学");
course.setScore("85");
student.addCourse(course);
System.out.println(BeanConvertUtils.beanToMap(student));
}
private class Student {
private String number;
private String name;
private List<Course> courses;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public void addCourse(Course course) {
if (courses == null) {
courses = new ArrayList<>();
}
courses.add(course);
}
}
private class Course {
private String name;
private String score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
}
跑一下看结果: