对象转map工具类BeanUtil

对象转map工具类BeanUtil1、2、当isAccessible()的结果是false时不允许通过反射访问private变量。packagecom.yung.ppapi.util;importjava.beans.BeanInfo;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;importjava.lang.re…

大家好,又见面了,我是你们的朋友全栈君。

1、

2、当isAccessible()的结果是false时不允许通过反射访问private变量。

package com.yung.ppapi.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanMap;
import org.springframework.beans.BeanUtils;

import com.yung.ppapi.integration.dto.YCPFExpressDTO;

/**
 * 
 * @author lisheng4
 *
 */
public class BeanUtil {
	
    public static <T> T clone(Object source, Class<T> type) {
        try {
        	if (source == null) {
        		return null;
        	}
            T target = type.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        } 
    } 
    public static <T> T clone(Object source, Class<T> type, String... ignoreProperties) {
        try {
        	if (source == null) {
        		return null;
        	}
            T target = type.newInstance();
            BeanUtils.copyProperties(source, target, ignoreProperties);
            return target;
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        } 
    } 
	
	/**
	 * 利用反射实现
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
		if (map == null) {
			return null;
		}

		Object obj = beanClass.newInstance();

		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			int mod = field.getModifiers();
			if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
				continue;
			}
			
			boolean accessFlag = field.isAccessible();
			field.setAccessible(true);// 允许通过反射访问该字段
			field.set(obj, map.get(field.getName()));
			field.setAccessible(accessFlag);
		}

		return obj;
	}
	
	/**
	 * 利用反射实现
	 * <li>空属性不转换
	 * <li>超过10万条数据不建议使用
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap(Object obj) throws Exception {

		if (obj == null) {
			return null;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		Field[] fields = obj.getClass().getDeclaredFields();
		for (int i = 0, len = fields.length; i < len; i++) {
			String varName = fields[i].getName();
			boolean accessFlag = fields[i].isAccessible();
			fields[i].setAccessible(true);// 允许通过反射访问该字段

			Object valueObj = fields[i].get(obj);
			if (valueObj != null) {
				map.put(varName, valueObj);
			}
			fields[i].setAccessible(accessFlag);
		}
		return map;
	}
	
	/**
	 * 利用java.beans.Introspector实现
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject2(Map<String, Object> map, Class<?> beanClass) throws Exception {    
	    if (map == null)
	        return null;    

	    Object obj = beanClass.newInstance();  

	    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
	    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
	    for (PropertyDescriptor property : propertyDescriptors) {  
	        Method setter = property.getWriteMethod();    
	        if (setter != null) {  
	            setter.invoke(obj, map.get(property.getName()));   
	        }  
	    }  
	    return obj;  
	}    
	 
	/**
	 * 利用java.beans.Introspector实现
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap2(Object obj) throws Exception {    
	    if(obj == null)  
	        return null;      

	    Map<String, Object> map = new HashMap<String, Object>();   

	    BeanInfo beanInfo = Introspector.getBeanInfo(obj.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(obj) : null;  
	        map.put(key, value);  
	    }    

	    return map;  
	} 
	
	/**
	 * 利用org.apache.commons.beanutils.BeanUtils实现
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject3(Map<String, Object> map, Class<?> beanClass) throws Exception {    
	    if (map == null)  
	        return null;  

	    Object obj = beanClass.newInstance();  
	    org.apache.commons.beanutils.BeanUtils.populate(obj, map);  
	    return obj;  
	}    
	 
	/**
	 * 利用org.apache.commons.beanutils.BeanMap实现
	 * @param obj
	 * @return
	 */
	public static Map<?,?> objectToMap3(Object obj) {  
	    if(obj == null)  
	        return null;   

	    return new BeanMap(obj);  
	} 

	
//	public static void main(String[] args) throws Exception {
//		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
//		List<Map<String,Object>> mapList2 = new ArrayList<Map<String,Object>>();
//		List<Map<String,Object>> mapList3 = new ArrayList<Map<String,Object>>();
//		long t11 = System.currentTimeMillis();
//		for(int i=1;i<=100000;i++) {
//			mapList.add(objectToMap(new YCPFExpressDTO()));
//		}
//		long t12 = System.currentTimeMillis();
//		
//		long t21 = System.currentTimeMillis();
//		for(int i=1;i<10000;i++) {
//			mapList2.add((Map<String, Object>) objectToMap2(new YCPFExpressDTO()));
//		}
//		long t22 = System.currentTimeMillis();
//		
//		long t31 = System.currentTimeMillis();
//		for(int i=1;i<10000;i++) {
//			mapList3.add((Map<String, Object>) objectToMap3(new YCPFExpressDTO()));
//		}
//		long t32 = System.currentTimeMillis();
//		System.out.println(t12-t11);
//		System.out.println(t22-t21);
//		System.out.println(t32-t31);
//		//System.out.println(t32-t31);
//	}

}

 

 

参考文章:https://www.cnblogs.com/XuYiHe/p/6871799.html

参考文章:https://blog.csdn.net/o_nianchenzi_o/article/details/78022416

 

 

楼主这么辛苦,请使用楼主的推荐码领取支付宝红包吧,记得一定要消费掉哦。双赢^_^。

1、打开支付宝首页搜索“8282987” 立即领红包。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145337.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 不是单组分组函数「建议收藏」

    不是单组分组函数「建议收藏」问题:一:SELECT tablespace_name, SUM(bytes) freeFROM dba_free_space不是单组分组函数原因: 1、如果程序中使用了分组函数,则有两种情况可以使用:程序中存在group by,并指定了分组条件,这样可以将分组条件一起查询出来改为:  SELECT tablespace_name, SUM(bytes) freeFROM dba_free_spa…

    2022年6月30日
    34
  • seo绩效考核指标_kpi考核三大指标内容

    seo绩效考核指标_kpi考核三大指标内容想要知道SEO优化有没有效果,都是需要以网站数据为前提的,包括网站收录情况、关键词排名情况、网站流量的多少及网站访客转化情况等,来算出最终的投入产出比是多少。一、内容页面关键词排名考核指标利用原创内容矩阵可以实现对某一类长尾关键词的覆盖,也是达成目标的一个基础手段,为此你可以在数据监测软件中对这部分关键词进行定期跟踪,确保达到预期效果。二、外链的数量与质量高质量的原创内容是获取高质量外链的…

    2022年9月18日
    0
  • 如何通过 User-Agent 识别百度蜘蛛

    如何通过 User-Agent 识别百度蜘蛛如果有大量的百度蜘蛛抓取网站就需要注意了:有可能是其他爬虫伪造百度蜘蛛恶意抓取网站。如果遇到这种情况,这时候就需要查看日志来确定是不是真正的百度蜘蛛(baiduspider)。搜索引擎蜘蛛、用户访

    2022年7月3日
    52
  • 怎么理解JS Promise

    怎么理解JS Promise      由于昨天发了一篇关于setTimeout的文章,里面提到了Promise,那篇文章里没有解释Promise的用法和含义,因为昨天的我还没太懂Promise,所以没有在那篇文章继续解释Promise,然后今天的我总算是对Promise有所理解了,然后我来谈谈我学到的Promise的知识,因为是个人的理解,所以会不全面,请多包涵。一、何为Promise在MDNwebdo…

    2022年6月11日
    34
  • 把一个数据表导入另一个数据库_把一个表里的数据导入另一个表

    把一个数据表导入另一个数据库_把一个表里的数据导入另一个表文章作者:姜南(Slyar)文章来源:SlyarHome(www.slyar.com)转载请注明,谢谢合作。之前发了《表达式变量批量替换器batchSQL》这篇文章,有童鞋说导入数据用phpMyAdmin提供的csv导入功能不是更好。的确,导入数据进入mysql用这个功能非常好,不过如果需要进行批量操作的是update或者其他操作呢,例如要从新的excel里批量更新某一部分的数据,总不能全…

    2022年9月2日
    2
  • python的dropna_python–data.dropna[通俗易懂]

    python的dropna_python–data.dropna[通俗易懂]读取csv文件data=pd.read_csv(“”)1、删除全为空值的行或列data=data.dropna(axis=0,how=’all’)#行data=data.dropna(axis=1,how=’all’)#列2、删除含有空值的行或列data=data.dropna(axis=0,how=’any’)#行data=data.dropna(axis=1,how=’an…

    2022年9月17日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号