Luo Hao

Java实体类和map的转换

rehoni / 2020-06-29


Java反射对JavaBean体和泛型Map做互换

Map转为Bean
public <T, K, V> T map2Bean(Map<K, V> map, Class<T> beanCls) {
    // try catch未写
    T t = null;
    BeanInfo beanInfo = Introspector.getBeanInfo(beanCls.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    t = beanCls.newInstance();
    for (PropertyDescriptor property : propertyDescriptors) {
        String key = property.getName();
        if (map.containsKey(key)) {
            Object value = map.get(key);
            Method setter = property.getWriteMethod();
            setter.invoke(t, value);
        }
    }
    return t;
}
Bean转为Map
public <T, K, V> Map<String, Object> bean2Map(T bean) {
    // try catch未写
    Map<String, Object> map = new HashMap<>();
    if (bean == null) {
        return null;
    }
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor property : propertyDescriptors) {
        String key = property.getName();
        if (!"class".equalsIgnoreCase(key)) {
            Method getter = property.getReadMethod();
            Object value = getter.invoke(bean);
            map.put(key, value);
        }
    }
    return map;
}