对象转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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 1146 mysql_MySQL–ERROR 1146 (42S02):table doesn’t exist

    1146 mysql_MySQL–ERROR 1146 (42S02):table doesn’t existERROR1146(42S02):Table‘xxx’doesn’texist可能是很多人都遇到的问题,尤其在数据库迁移或备份的时候mysql数据目录结构mysql数据目录下有如下几个重要文件:ibdata1ib_logfile0ib_logfile1数据库xx以及该目录下的一系列.frm文件其中ib_logfile0和ib_logfile1是关于数据库的一些日志文件数据…

    2022年5月2日
    446
  • JAVA | StringUtils中 isNotEmpty 和 isNotBlank的区别[通俗易懂]

    JAVA | StringUtils中 isNotEmpty 和 isNotBlank的区别[通俗易懂]isNotEmpty和isNotBlank的区别

    2022年8月12日
    12
  • 如何用python画一个圆(python主要是做什么的)

    本文为大家分享了python实现画圆功能的实例代码,有需要的朋友请参考下文!importnumpyasnpimportmatplotlib.pyplotaspltfrommatplotlib.patchesimportPolygonimportmatplotlib.patchesasmpatchesfig=plt.figure(figsize=(16,8))ax=…

    2022年4月14日
    251
  • 理解GC

    理解GC

    2021年9月7日
    57
  • DropDownList DataBound事件

    DropDownList DataBound事件当我们在对DropDownList绑定数据的时候DropDownList1.DataTextField=””;DataTextField绑定要显示的值DropDownList1.DataValueField=””;DataValueField绑定value值可是当绑定的时候没有value值的话,value的值就会和Text值相等,可是我们value值又不想取文字形式的…

    2025年9月1日
    8
  • Win10 CMD命令大全—超好用快捷键

    Win10 CMD命令大全—超好用快捷键一、WindowsCMD命令大全1、按组合键Win(Windows图标键)+R键打开运行窗口,输入“cmd”按回车即可打开cmd命令提示符2、在窗口右击选择属性可进行个性化设置~命令功能1、calc启动计算器2、appwiz.cpl程序和功能3、certmgr.msc证书管理实用程序4、charmap启动字符映射表5、chkdsk.exeChkdsk磁盘检查(管理员身份运行命令提示符)6、cleanmgr打开磁盘清理工具7、

    2022年5月17日
    877

发表回复

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

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