反射映射实体类进行装配
package com.erju.springbootStudy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import lombok.Data;
@SpringBootTest
@SuppressWarnings("all")
class SpringbootStudyApplicationTests {
@Data
static class UserInfo {
private Integer id;
private String userId;
private String userName;
private String img;
private Integer gender;
private LocalDate birthday;
private Integer height;
private String hometown;
}
public static UserInfo buildUserInfo(Map userInfoMap) throws Exception{
UserInfo userInfo = new UserInfo();
Class uInfo = userInfo.getClass();
Set keySet = userInfoMap.keySet();
Iterator iterator = keySet.iterator();
String next = (String) iterator.next();
String first = next.substring(0,1).toUpperCase();
Class paramType = Class.forName(uInfo.getDeclaredField(String.valueOf(next)).getType().getName());
Method method = uInfo.getMethod("set"+first+next.substring(1),paramType);
String name = paramType.getName();
if(("java.lang.Integer").equals(name) ){
method.invoke(userInfo,Integer.parseInt((String) userInfoMap.get(next)));
}
if(("java.time.LocalDate").equals(name)){
method.invoke(userInfo,LocalDate.parse((String) userInfoMap.get(next)));
}else
{
method.invoke(userInfo,userInfoMap.get(next));
}
return userInfo;
}
@Test
void testLogin() throws Exception {
UserInfo userInfo = new UserInfo();
Map userInfoMap = new HashMap();
userInfoMap.put("birthday", "1999-01-01");
System.out.println(buildUserInfo(userInfoMap));
}
}