1.动态给对象里的属性赋值
//根据反射生成AccountFramework对象
private AccountFramework createAccountFramework(List<AccountSchoolPersonnelFieldRequest> fields) {
try {
Class<AccountFramework> clazz = AccountFramework.class;
//创建实例
AccountFramework instance = clazz.getDeclaredConstructor().newInstance();
fields.stream().forEach(field -> {
String name = field.getColumnName();
String value = field.getValue();
try {
//获取字段类型
Class<?> type = clazz.getDeclaredField(name).getType();
//首字母大写
String replace = name.substring(0, 1).toUpperCase()+ name.substring(1);
//获得setter方法
Method setMethod = clazz.getMethod("set" + replace, type);
setMethod.invoke(instance, value);
} catch (Exception e) {
e.printStackTrace();
}
});
return instance;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Data
public class AccountSchoolPersonnelFieldRequest {
@ApiModelProperty(value = "列名")
private String columnName;
@ApiModelProperty(value = "值")
private String value;
}