• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

【java_ Using introspective technology to simulate BeanUtils

King Wang

1 月 3, 2022

primary BeanUtils Source

import org.apache.commons.beanutils.BeanUtils;

primary BeanUtils Common method

populate(Object bean, Map<String, ? extends Object> properties); // Pass in Map Parameter injection bean
 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) {

// The goal is : Get the corresponding... According to the field name set Method , This is another technology called todo introspection , adopt Class Object parsing set Method 
PropertyDescriptor descriptor = null;
try {

descriptor = new PropertyDescriptor(key, clazz);
} catch (IntrospectionException e) {

e.printStackTrace();
}
assert descriptor != null;
Method writeMethod = descriptor.getWriteMethod();// obtain set Method 
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) {

// Get the descriptor of the class ,key Pass on setXXX/getXXX Of XXX
PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);
// obtain set Method 
Method writeMethod = descriptor.getWriteMethod();
// Reflection call Bean Object's set Method , from map Get method parameters 
writeMethod.invoke(t, map.get(key));
}

发表回复