JAVA内省案例:javabean与map互相转换

javabean 转 map

public static Map bean2map(Object obj) {
    Map map=new HashMap<>();
    try {
        Class clazz = obj.getClass();
        BeanInfo bi=Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] pds=bi.getPropertyDescriptors();

        for(PropertyDescriptor pd:pds){
            String name=pd.getName();
            if("class".equals(name)){
                continue;
            }
            Method m=pd.getReadMethod();
            if(m!=null){
                Object ret=m.invoke(obj);
                map.put(name, ret);
//                    System.out.println(o);
            }
        }

    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return map;
}

map 转 javabean

public static void map2bean(Map<String ,Object> map,Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
    if(map == null || map.isEmpty()){
        return;
    }
    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for(PropertyDescriptor pro : propertyDescriptors) {
        if("class".equals(pro.getName())){
            continue;
        }
        // 根据属性名,从map中取出value
        Object value = map.get(pro.getName());
        // 如果value为null,则忽略
        if(value == null){
            continue;
        }
        // 获取setter方法的形参
        Class<?>[] parameterTypes = pro.getWriteMethod().getParameterTypes();
        if(parameterTypes!=null && parameterTypes.length == 1){
            Class<?> parameterType = parameterTypes[0];
            // 判断形参类型与 map中的value类型是否相同,相同则调用 setter 方法
            if( parameterType == value.getClass() ){
                pro.getWriteMethod().invoke(obj, value);
            }
        }

    }
}

测试

public class TestBeanUtil {
    public static void main(String[] args) {
        Map map=new HashMap();
        map.put("name","java从入门到入坑");
        map.put("gender","匿名");

        Person person = new Person();

        try {
            BeanUtil.map2bean(map,person);
            System.out.println();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

原文出处:/show_1IX1jjC9H4dc.html