自定义类
/**
* @date 2023/12/19 11:20
*/
public class Person {
private String name;
private String sex;
public Person() {
}
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
}
工具方法
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* Map转为自定义对象
*
* @date 2023/12/21 14:17
*/
public class MapToObjUtils {
/**
* Map转为自定义对象
* <p>
* fastJson方式
*
* @param map
* @param clazz
* @return
*/
public static <T> T mapToObj1(Map<String, Object> map, Class<T> clazz) {
T object = null;
try {
object = JSON.parseObject(JSON.toJSONString(map), clazz);
} catch (Exception e) {
// 异常处理
}
return object;
}
/**
* Map转为自定义对象
* <p>
* BeanUtils.populate方式
*
* @param map
* @param person
* @return
*/
public static void mapToObj2(Map<String, Object> map, Person person) {
try {
BeanUtils.populate(person, map);
} catch (IllegalAccessException | InvocationTargetException e) {
// 异常处理
}
}
/**
* Map转为自定义对象
* <p>
* 反射方式
*
* @param map
* @param clazz
* @return
*/
public static <T> T mapToObj3(Map<String, Object> map, Class<T> clazz) {
try {
T object = clazz.getDeclaredConstructor().newInstance();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
}
return object;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Map<String, Object> results = new HashMap<>();
results.put("name", "小明");
results.put("sex", "m");
long start1 = System.currentTimeMillis();
Person person1 = MapToObjUtils.mapToObj1(results, Person.class);
long end1 = System.currentTimeMillis();
long start2 = System.currentTimeMillis();
Person person2 = new Person();
MapToObjUtils.mapToObj2(results, person2);
long end2 = System.currentTimeMillis();
long start3 = System.currentTimeMillis();
Person person3 = MapToObjUtils.mapToObj3(results, Person.class);
long end3 = System.currentTimeMillis();
System.out.println("Map转为自定义对象 fastJson方式耗时 " + (end1 - start1) + " 毫秒");
System.out.println("Map转为自定义对象 BeanUtils.populate方式耗时 " + (end2 - start2) + " 毫秒");
System.out.println("Map转为自定义对象 反射方式耗时 " + (end3 - start3) + " 毫秒");
}
}
结果: