美文网首页
Map和Bean转换

Map和Bean转换

作者: wangpeng123 | 来源:发表于2018-04-25 17:47 被阅读0次

为了使用redis hash类型对bean和map进行转换

import net.iyouqu.union.mongo.entity.enums.BookType;
import org.bson.types.ObjectId;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 对象转换
 * Created by wangpeng on 2018/4/24.
 */
public class ObjectUtil {
    /**
     * objectid包路径
     */
    private final static String OBJECTID_PACKAGE = "org.bson.types.ObjectId";

    /**
     * booktype包路径
     */
    private final static String BOOK_TYPE_PACKAGE = "net.iyouqu.union.mongo.entity.enums.BookType";
    /**
     * 日期包路径
     */
    private final static String DATE_PACKAGE = "java.util.Date";
    /**
     * float
     */
    private final static String FLOAT = "float";

    /**
     * 将一个 JavaBean 对象转化为一个  Map
     *
     * @param bean 要转化的JavaBean 对象
     * @return 转化出来的  Map 对象
     * @throws IntrospectionException    如果分析类属性失败
     * @throws IllegalArgumentException
     * @throws IllegalAccessException    如果实例化 JavaBean 失败
     * @throws InvocationTargetException 如果调用属性的 setter 方法失败
     */
    public static Map<String, Object> convertBean(Object bean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);
                if (result != null) {
                    if (result instanceof Date) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        result = simpleDateFormat.format(result);
                    }
                    if (result instanceof ObjectId) {
                        result = result.toString();
                    }
                    returnMap.put(propertyName, result);
                }
            }
        }
        return returnMap;
    }


    /**
     * 将一个 Map 对象转化为一个 JavaBean
     *
     * @param type 要转化的类型
     * @param map  包含属性值的 map
     * @return 转化出来的 JavaBean 对象
     * @throws IntrospectionException    如果分析类属性失败
     * @throws IllegalAccessException    如果实例化 JavaBean 失败
     * @throws InstantiationException    如果实例化 JavaBean 失败
     * @throws InvocationTargetException 如果调用属性的 setter 方法失败
     */
    public static Object convertMap(Class type, Map map)
            throws IntrospectionException, IllegalAccessException,
            InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
        Object obj = type.newInstance(); // 创建 JavaBean 对象

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                Class<?> propertyType = descriptor.getPropertyType();

                // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                Object value = map.get(propertyName);
                if (propertyType.isEnum()) {
                    Object[] objs = propertyType.getEnumConstants();
                    for (Object object : objs) {
                        if (value.toString().equals(object.toString())) {
                            value = object;
                            break;
                        }
                    }
                } else if (DATE_PACKAGE.equals(descriptor.getPropertyType().getName())) {
                    value = new Date(Long.valueOf(value.toString()));
                } else {
                    Constructor<?> constructor = propertyType.getConstructor(String.class);
                    value = constructor.newInstance(value.toString());
                }
                Object[] args = new Object[1];
                args[0] = value;
                try {
                    descriptor.getWriteMethod().invoke(obj, args);
                } catch (InvocationTargetException e) {
                    log.info("缺少set方法", propertyName);
                }
            }
        }
        return obj;
    }
}
/**
     * 将一个 数组根据参数名转化 转化为一个 JavaBean
     *
     * @param type          要转化的类型
     * @param propertyNames 属性名
     * @param values        值
     * @return 转化出来的 JavaBean 对象
     * @throws IntrospectionException 如果分析类属性失败
     * @throws IllegalAccessException 如果实例化 JavaBean 失败
     * @throws InstantiationException 如果实例化 JavaBean 失败
     */
    public static Object convertBean(Class type, String[] propertyNames, Object[] values)
            throws IntrospectionException, IllegalAccessException,
            InstantiationException {
        Object obj = type.newInstance(); // 创建 JavaBean 对象

        for (int i = 0; i < propertyNames.length; i++) {
            PropertyDescriptor descriptor = new PropertyDescriptor(propertyNames[i], type);
            try {
                descriptor.getWriteMethod().invoke(obj, values[i]);
            } catch (InvocationTargetException e) {
                logger.info("缺少set方法", propertyNames[i]);
            }
        }
        return obj;
    }

相关文章

网友评论

      本文标题:Map和Bean转换

      本文链接:https://www.haomeiwen.com/subject/dzvylftx.html