import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* java map转实体类
*/
public class MapToEntityConverter {
public static <T> T convertMapToEntity(Map<String, Object> map, Class<T> entityClass) {
T entity;
try {
entity = entityClass.newInstance();
Field[] fields = entityClass.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
if (map.containsKey(fieldName)) {
field.setAccessible(true);
field.set(entity, map.get(fieldName));
}
}
} catch (Exception e) {
throw new RuntimeException("Error converting map to entity", e);
}
return entity;
}
public static void main(String[] args) {
//Map<String, Object> map = Map.of("name", "John Doe", "age", 30);
Map<String, Object> map = new HashMap<String, Object>() {
{
put("name", "John Doe");
put("age", 30);
}
};
//map.forEach((k,v)-> System.out.println(k));
Person person = convertMapToEntity(map, Person.class);
System.out.println(person.getName()); // John Doe
System.out.println(person.getAge()); // 30
}
}
class Person {
private String name;
private int age;
// getters and setters
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;
}
}
参考:
百度搜索AI回答