码迷,mamicode.com
首页 > 其他好文 > 详细

对象属性封装到map中

时间:2016-10-29 12:04:22      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:pre   static   style   stat   access   return   object   nbsp   not   

package cn.itsource.crm.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;

public class CommUtil {

    /**
     * 把指定的复杂对象属性,按照指定的内容,封装到新的map中
     * @param source 目标对象
     * @param ps     需要封装到map中的属性
     * @return
     */
    public static Map<String, Object> obj2map(Object source, String[] ps) {
        Map<String, Object> map = new HashMap<>();
        if (source == null)
            return null;
        if (ps == null || ps.length < 1) {
            return null;
        }
        for (String p : ps) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(
                    source.getClass(), p);
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass()
                            .getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source, new Object[0]);
                    map.put(p, value);
                } catch (Exception ex) {
                    throw new RuntimeException(
                            "Could not copy properties from source to target",
                            ex);
                }
            }
        }
        return map;
    }

    
}

 

对象属性封装到map中

标签:pre   static   style   stat   access   return   object   nbsp   not   

原文地址:http://www.cnblogs.com/zzllx/p/6009993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!