对象转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)
上一篇 2022年5月17日 下午5:00
下一篇 2022年5月17日 下午5:00


相关推荐

  • IOS 最新邓白氏编码申请

    IOS 最新邓白氏编码申请iOS 开发邓白氏编码申请流程 前言 邓白氏编码不是所有账号都需要的 如果你只是申请个人账号 不需要显示公司的信息 那就不需要邓白氏编码 直接 nbsp 99 美元那个个人的就可以 如果你 nbsp App 需要显示的是公司的信息 那就需要了 apple 三种开发者账号的区别 1 个人开发者 可以上传 store 99 最多支持 100 台测试设备 2 公司开发者账号 也叫组织开发者账号 可以上传 appstore 产品

    2026年3月17日
    6
  • 最好用的java开发工具_应用开发工具

    最好用的java开发工具_应用开发工具Java开发者常常都会想办法如何更快地编写Java代码,让编程变得更加轻松。目前,市面上涌现出越来越多的高效编程工具。所以,以下总结了一系列工具列表,其中包含了大多数开发人员已经使用、正在使用或

    2022年8月3日
    7
  • react native监听返回_invalid handler for event

    react native监听返回_invalid handler for eventreact native错误排查-TypeError: window.deltaUrlToBlobUrl is not a function

    2022年4月22日
    83
  • 深入了解epoll模型 — 开卷有益

    深入了解epoll模型 — 开卷有益希望打开此篇对你有所帮助

    2026年3月17日
    2
  • linux mysql1146_MySQL主从同步及错误1146解决办法

    linux mysql1146_MySQL主从同步及错误1146解决办法在实际使用MySQL的时候我们有时要增加一些新的库进行主从同步,所以可以通过修改my.cnf文件以及在主库上添加用户连接权限就可以实现主从同步,而在做主从同步的时候碰到几个问题这里就和大家说一下,至于如何构建主从同步这里就不再多说了,相信在网上能找到一大堆,这里就稍稍提几个关键点,在从库下的my.cnf添加如下几行:server-id=2#一般主库是1,从库可以除1以外的数字log-bin=m…

    2022年6月4日
    95
  • java文件处理(3)——实现文件复制和文件移动「建议收藏」

    java文件处理(3)——实现文件复制和文件移动「建议收藏」任务要求:通过二进制流的操作方式把程序调整为可以实现对任何类型文件进行文件复制(而不是调用windows命令行的内部命令copy)。通过二进制流的操作方式把程序调整为可以实现对任何类型文件进行文件移动(而不是调用windows命令行的外部命令move)。1.介绍InputStream和OutputStreamInputStream和OutputStream是抽象类,是所有字节输入流和输…

    2022年6月22日
    30

发表回复

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

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