primary BeanUtils Source
import org.apache.commons.beanutils.BeanUtils;
primary BeanUtils Common method
populate(Object bean, Map<String, ? extends Object> properties);
public void getBean() {
HashMap<String, String> map = new HashMap<>();
map.put("age", "19");
map.put("name", "kkk");
map.put("address","shenzhen");
Student student = new Student();
try {
BeanUtils.populate(student, map);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(student);
}
primary BeanUtils Application scenarios
servlet Get request parameters , Encapsulated into JavaBean
Map<String, String[]> parameterMap = request.getParameterMap();
Contact contact = new Contact();
try {
BeanUtils.populate(contact, parameterMap);
} catch (Exception e) {
e.printStackTrace();
}
Use introspective technology to imitate the implementation BeanUtils
public static <T> T populate(T t, HashMap<String, String> map) {
Set<String> keys = map.keySet();
Class clazz = t.getClass();
for (String key : keys) {
PropertyDescriptor descriptor = null;
try {
descriptor = new PropertyDescriptor(key, clazz);
} catch (IntrospectionException e) {
e.printStackTrace();
}
assert descriptor != null;
Method writeMethod = descriptor.getWriteMethod();
try {
writeMethod.invoke(t, map.get(key));
} catch (Exception e) {
e.printStackTrace();
}
}
return t;
}
The key API
public static <T> T populate(T t, HashMap<String, String> map) {
PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);
Method writeMethod = descriptor.getWriteMethod();
writeMethod.invoke(t, map.get(key));
}