转载自 https://blog.csdn.net/u013905744/article/details/73167861
需求:
有一个Map对象
[java] view plain copy
- Map map = new HashMap<>();
- map.put("name", "bellychang");
- map.put("likes", new String[]{"football", "basketball"});
希望实现一个通用方法,将其转换为如下的JavaBean
[java] view plain copy
- public class SimpleBean {
- private String name;
- private String[] likes;
- public SimpleBean() {
- }
- public SimpleBean(String name, String[] likes){
- this.name = name;
- this.likes = likes;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String[] getLikes() {
- return likes;
- }
- public void setLikes(String[] likes) {
- this.likes = likes;
- }
- @Override
- public String toString() {
- return "SimpleBean{"
- "name='" name '''
- ", likes=" Arrays.toString(likes)
- '}';
- }
- }
工具类
[java] view plain copy
- public static T convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException,
- InstantiationException, InvocationTargetException {
- BeanInfo beanInfo = null; // 获取类属性
- T obj = null;
- beanInfo = Introspector.getBeanInfo(type);
- // 创建 JavaBean 对象
- obj = type.newInstance();
- // 给 JavaBean 对象的属性赋值
- // 获取属性的描述器(PropertyDescriptor)
- PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
- // 通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后就可以通过反射机制来调用这些方法
- for (int i = 0; i < propertyDescriptors.length; i ) {
- PropertyDescriptor descriptor = propertyDescriptors[i];
- String propertyName = descriptor.getName();
- if (map.containsKey(propertyName)) {
- // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
- Object value = map.get(propertyName);
- Object[] args = new Object[1];
- //getPropertyType得到属性类型
- if (descriptor.getPropertyType() == Long.class) {
- args[0] = Long.parseLong(value.toString());
- } else if (descriptor.getPropertyType() == Integer.class) {
- args[0] = Integer.valueOf(value.toString());
- } else {
- args[0] = value;
- }
- //getWriteMethod()得到此属性的set方法----Method对象,然后用invoke调用这个方法
- descriptor.getWriteMethod().invoke(obj, args);
- }
- }
- return obj;
- }
测试类
[java] view plain copy
- @Test
- public void testConvertMap() throws Exception {
- //将一个Map对象转换为JavaBean
- Map map = new HashMap<>();
- map.put("name", "changliang");
- map.put("likes", new String[]{"football", "basketball"});
- SimpleBean simpleBean = BeanToMapUtil.convertMap(SimpleBean.class, map);
- System.out.println(simpleBean);
- }
注意事项:
1. Map的key与JavaBean的key一致
2. JavaBean中要有空的构造函数,以及get,set方法
参考:java 中的内省机制