场景假设:
1.给定字符串,请自行举一反三传入集合或其他类型
String string = "a|b|c|d";
2实体类
public class uesr{
private String name;
private String age;
private String id;
private String sex;
//get/set 此处省略
3工具类
public Object ArrayToPojo(String repeatfile, Object obj) {
List<String> important = new ArrayList<String>();
String[] ticket = repeatfile.split("\\|");
Collections.addAll(important, ticket);
// 利用反射获取实体类的所有方法
Class cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
if (fields.length >= important.size()) {
for (int j = 0; j < important.size(); j++) {
Field f = fields[j];
f.setAccessible(true);
try {
// 获取数据类型
//String type = f.getGenericType().toString();
// 获取属性名称
//String name = f.getName();
// 首字母大写
// String getName = name.replaceFirst(name.substring(0, 1),
// name.substring(0, 1).toUpperCase());
f.set(obj, f.getType().getConstructor(f.getType()).newInstance(important.get(j)));
} catch (Exception e) {
System.out.println("....动态给实体类赋值出现问题....");
}
}
} else {
System.out.println("动态配置过程中,数组的参数个数大于实体类的属性个数...无法自动装配");
}
System.out.println(obj.toString());
return obj;
}
4.main 方法
本文 main 方法省略不写
调取方法
Object obj = new user();
// 调取时要保证 字符串中截取后的数组长度,或集合长度 不大于 实体类的字段个数
调取工具类
ArrayToPojo(string,obj);