通过反射将map类型转为实体对象
背景
有一个从mySQL查询出的一批数据是Map类型,现在需要将这些map类型的数据处理为一个实体对象,存入到es中。旧方法是通过key将每一个value取出来,然后再放入对象中。现在想要通过反射的方法对其进行改造,直接转为需要的类型。
模拟实体类如下
public class Student {
Long id;
String name;
Integer age;
public Student(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
通过反射转换代码如下
public class map2Entity {
public static void main(String[] args) {
//使用List模拟一张表
List<Map<String, Object>> table = new ArrayList<>();
//map数据(属性:值)
Map<String, Object> map = new HashMap<>();
map.put("ID", 10000L);
map.put("NAME", "cjy");
map.put("AGE", 23);
table.add(map);
//反射转换
Student student = null;
try {
//通过无参构造一个对象
student = Student.class.getDeclaredConstructor().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//获取所有字段
try {
//获取已声明的字段
Field[] declaredFields = Student.class.getDeclaredFields();
for (Field field : declaredFields) {
//获取修饰符,用数字表示
int modifiers = field.getModifiers();
//判断是否为final或者static,如果是,不能对其赋值
if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)){
continue;
}
//通过setAccessible(true)的方式关闭安全检查就可以达到提升反射速度的目的
field.setAccessible(true);
//获取value
Object value = map.get(field.getName().toUpperCase());
//类型判断,丰富
if (value instanceof Long){
//为空则赋值为0
value = value == null ? 0 : value;
}else if (value instanceof Integer){
//为空则赋值为0
value = value == null ? 0 : value;
}else if (value instanceof String){
//为空则赋值为""
value = value == null ? "" : value;
}
if (value != null){
//设置值
field.set(student, value);
}
}
}catch (IllegalAccessException e) {
System.out.println("转换异常!");
}
System.out.println(student);
}
}
getModifiers()方法返回int类型值表示该字段的修饰符。