在开发数据解析的功能时,会有将目标数据解析到多个字段中的场景,比如将以下的数据解析入库:
public class UserTo implements Serializable {
private static final Long serialVersionUID = 1L;
private String name;
private String age;
private String score;
}
String str = "name:zhangsan,age:30,score:100";
常规做法是
user.setAge(str.split(",")[0].split(":")[1]);
user.setName(str.split(",")[1].split(":")[1]);
user.setScore(str.split(",")[2].split(":")[1]);
当字段较多或者字段变更比较频繁的时候,可以使用反射获取实体属性,动态赋值:
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
String str = "name:zhangsan,age:30,score:100";
Class c1 = Class.forName("com.model.UserTo");
UserTo user = (UserTo) c1.newInstance();
String[] arr = str.split(",");
for(String arrStr : arr){
Field item = c1.getDeclaredField(arrStr.split(":")[0]);
item.setAccessible(true);
item.set(user,arrStr.split(":")[1]);
}
System.out.println(JSON.toJSONString(user));
}
这样做的好处:
1.更加轻量,后续字段增多了不需要重复开发,只要确保表字段和来源数据一致即可,省去重新开发的
2.代码简洁,容易维护
缺点:
1.字段如果有二次加工不太方便
|