java常见的数据类型互转

1.Array转List

String[] s = new String[]{"A", "B", "C", "D","E"};
List list = Arrays.asList(s);

2.List转Array

String[] arrays = list.toArray(new String[0]);

3.Array转Set

s = new String[]{"A", "B", "C", "D","E"};
set = new HashSet<>(Arrays.asList(s));

4.Set转Array

dest = set.toArray(new String[0]);

5.Map转Bean

/**
 * 使用Introspector,map集合成javabean
 *
 * @param map       map
 * @param beanClass bean的Class类
 * @return bean对象
 */
public static  T mapToBean(Map map, Class beanClass) {
 
    if (MapUtils.isEmpty(map)) {
        return null;
    }
 
    try {
        T t = beanClass.newInstance();
 
        BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
                setter.invoke(t, map.get(property.getName()));
            }
        }
        return t;
    } catch (Exception ex) {
        log.error("########map集合转javabean出错######,错误信息,{}", ex.getMessage());
        throw new RuntimeException();
    }
 
}

6.Bean转Map


/**
 * 使用Introspector,对象转换为map集合
 *
 * @param beanObj javabean对象
 * @return map集合
 */
public static Map beanToMap(Object beanObj) {
 
    if (null == beanObj) {
        return null;
    }
 
    Map map = new HashMap<>();
 
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(beanObj) : null;
            map.put(key, value);
        }
 
        return map;
    } catch (Exception ex) {
        log.error("########javabean集合转map出错######,错误信息,{}", ex.getMessage());
        throw new RuntimeException();
    }
}

你可能感兴趣的:(转换,java)