day27(反射之内省机制实现BeanUtils)

时间:2021-09-06 21:36:53

    使用内省方式来实现beanUtils往对象里面存值

public class BeanInfoUtil2 {
public static void setPropertyByIntrospector(Object userInfo,
Map<String,Object> map) throws Exception {
//map key=name value=value
BeanInfo beanInfo = Introspector.getBeanInfo(userInfo.getClass());
PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();
if (proDescrtptors != null && proDescrtptors.length > 0) {
for (PropertyDescriptor propDesc : proDescrtptors) {
Method method = propDesc.getWriteMethod();
if (null==method) {
continue;
}
for (String keys : map.keySet()) {
if (method.getName().equals("set"+keys)) {
method.invoke(userInfo, map.get(keys));
}
}
}
}
}
}

    测试类

                Student s=new Student();
Map<String,Object> map=new HashMap<String,Object>();
map.put("Name", "张三");
map.put("Age", 15);
BeanInfoUtil2.setPropertyByIntrospector(s, map);
System.out.println(s.getName());
System.out.println(s.getAge());