前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >对象转map工具类BeanUtil

对象转map工具类BeanUtil

作者头像
全栈程序员站长
发布2022-08-30 08:38:54
4730
发布2022-08-30 08:38:54
举报
文章被收录于专栏:全栈程序员必看

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

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

代码语言:javascript
复制
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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档