代码优化篇-数组转对象

今天工作做完了,看了下团队的数据接收代码,简直惨不忍睹。

场景如下:业务平台通过http接口传递过来的单位数据,切割成数组后一个个参数去取,然后一堆 if、else if去校验,对于这种 其实转为一个对象会更简单,而且重用性提高很多。

package com.powersi.biz.collectinfo.mvc;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class EntityUtils {
	private static final Logger logger = LoggerFactory.getLogger(EntityUtils.class);
	
	/**
     * 将数组数据转换为实体类
     * 此处数组元素的顺序必须与实体类构造函数中的属性顺序一致
     *
     * @param list  数组对象集合
     * @param clazz 实体类
     * @param <T>   实体类
     * @param model 实例化的实体类
     * @return 实体类集合
     */
	public static <T> List<T> castEntityList(List<Object[]> list, Class<T> clazz, Object model) {
        List<T> returnList = new ArrayList<T>();
        if (list.isEmpty()) {
            return returnList;
        }
        //获取每个数组集合的元素个数
        Object[] co = list.get(0);

        //获取当前实体类的属性名、属性值、属性类别
        List<Map<String, Object>> attributeInfoList = getFiledsInfo(model);
        //创建属性类别数组
        Class[] c2 = new Class[attributeInfoList.size()];
        //如果数组集合元素个数与实体类属性个数不一致则发生错误
        if (attributeInfoList.size() != co.length) {
            return returnList;
        }
        //确定构造方法
        for (int i = 0; i < attributeInfoList.size(); i++) {
            c2[i] = (Class) attributeInfoList.get(i).get("type");
        }
        try {
            for (Object[] o : list) {
                Constructor<T> constructor = clazz.getConstructor(c2);
                returnList.add(constructor.newInstance(o));
            }
        } catch (Exception ex) {
        	logger.error("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage());
            return returnList;
        }
        return returnList;
    }
	
	/**
     * 功能描述: 〈数组转对象〉
     *
     * @param clazz   实体类
     * @param objects 数组
     * @param <T>     实体类
     * @param model   实例化的实体类
     * @return : T
     * @author : taoGuoGuo 2020/6/10 15:05
     */
	public static <T> T castEntity(Object[] objects, Class<T> clazz, Object model) {
        T t = null;
        List<Object[]> list = new ArrayList<>();
        if (objects.length > 0) {
            list.add(objects);
        }
        List<T> ts = castEntityList(list, clazz, model);
        if (!CollectionUtils.isEmpty(ts)) {
            t = ts.get(0);
        }
        return t;
    }
	
	 /**
     * 根据属性名获取属性值
     *
     * @param fieldName 属性名
     * @param modle     实体类
     * @return 属性值
     */
    private static Object getFieldValueByName(String fieldName, Object modle) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = modle.getClass().getMethod(getter);
            return method.invoke(modle);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取属性类型(type),属性名(name),属性值(value)的map组成的list
     *
     * @param model 实体类
     * @return list集合
     */
    private static List<Map<String, Object>> getFiledsInfo(Object model) {
        Field[] fields = model.getClass().getDeclaredFields();
        List<Map<String, Object>> list = new ArrayList<>(fields.length);
        Map<String, Object> infoMap = null;
        for (Field field : fields) {
            infoMap = new HashMap<>(3);
            infoMap.put("type", field.getType());
            infoMap.put("name", field.getName());
            infoMap.put("value", getFieldValueByName(field.getName(), model));
            if (!"serialVersionUID".equals(field.getName())) {
                list.add(infoMap);
            }
        }
        return list;
    }
    
    /**
     * 功能描述: 〈list分页〉
     *
     * @param list     待分页对象集合
     * @param pageable 分页参数
     * @return : org.springframework.data.domain.Page<T>
     * @author : yangyu 2019/12/4 15:16
     */
    public static <T> Page<T> listConvertToPage(List<T> list, Pageable pageable) {
        int start = (int) pageable.getOffset();
        int end = (start + pageable.getPageSize()) > list.size() ? list.size() : (start + pageable.getPageSize());
        return new PageImpl<>(list.subList(start, end), pageable, list.size());
    }

    /**
     * 功能描述: 〈对象转字符串数组〉
     *
     * @param str1 需要转化的字段
     * @return : java.lang.String[]
     * @author : taoGuoGuo 2020/6/10 15:05
     */
    public static <T> String[] object2StrArray(T t, String[] str1) {
        String[] str2 = null;
        List<String> list2 = new ArrayList<>();
        if ((t!=null && !t.equals("")) && str1.length > 0) {
            Field[] fields = t.getClass().getDeclaredFields();
            // 需要转化的字段
            for (String s : str1) {
                for (Field field : fields) {
                    // 私有属性必须设置访问权限
                    field.setAccessible(true);
                    try {
                        if (s.equals(field.getName())) {
                            Object o = field.get(t);
                            if (o instanceof LocalDateTime) {
                                LocalDateTime time = (LocalDateTime) o;
                                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                list2.add(dtf.format(time));
                            } else if (o instanceof LocalDate) {
                                LocalDate date = (LocalDate) o;
                                list2.add(date.toString());
                            } else {
                                list2.add(o == null ? "" : o.toString());
                            }
                            break;
                        }
                    } catch (Exception e) {
                        list2.add("");
                    }
                }
            }
            if (!CollectionUtils.isEmpty(list2)) {
                str2 = list2.toArray(new String[0]);
            }

        }
        return str2;
    }

    /**
     * 功能描述: 〈对象转字符串数组〉
     *
     * @param str 需要转化的字段
     * @return : java.lang.String[]
     * @author : taoGuoGuo 2020/6/10 15:05
     */
    public static <T> List<String[]> object2StrArray(List<T> t, String[] str) {
        List<String[]> list = new ArrayList<>();
        t.forEach(e -> {
            list.add(object2StrArray(e, str));
        });
        return list;
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
        if (map == null) {
            return null;
        }
        T obj = null;
        try {
            obj = beanClass.newInstance();
            BeanUtils.populate(obj, map);
        } catch (Exception e) {
            return null;
        }

        return obj;
    }


}

我们测试一下:

测试实体:

package com.powersi.biz.collectinfo.mvc;

public class DemoEntity {
	
	private String aa01;
	private String aa02;
	private String aa03;
	private String aa04;
	private String aa05;
	private String aa06;
	
	public DemoEntity() {
		super();
	}

	public DemoEntity(String aa01, String aa02, String aa03, String aa04, String aa05, String aa06) {
		super();
		this.aa01 = aa01;
		this.aa02 = aa02;
		this.aa03 = aa03;
		this.aa04 = aa04;
		this.aa05 = aa05;
		this.aa06 = aa06;
	}

	public String getAa01() {
		return aa01;
	}

	public void setAa01(String aa01) {
		this.aa01 = aa01;
	}

	public String getAa02() {
		return aa02;
	}

	public void setAa02(String aa02) {
		this.aa02 = aa02;
	}

	public String getAa03() {
		return aa03;
	}

	public void setAa03(String aa03) {
		this.aa03 = aa03;
	}

	public String getAa04() {
		return aa04;
	}

	public void setAa04(String aa04) {
		this.aa04 = aa04;
	}

	public String getAa05() {
		return aa05;
	}

	public void setAa05(String aa05) {
		this.aa05 = aa05;
	}

	public String getAa06() {
		return aa06;
	}

	public void setAa06(String aa06) {
		this.aa06 = aa06;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((aa01 == null) ? 0 : aa01.hashCode());
		result = prime * result + ((aa02 == null) ? 0 : aa02.hashCode());
		result = prime * result + ((aa03 == null) ? 0 : aa03.hashCode());
		result = prime * result + ((aa04 == null) ? 0 : aa04.hashCode());
		result = prime * result + ((aa05 == null) ? 0 : aa05.hashCode());
		result = prime * result + ((aa06 == null) ? 0 : aa06.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DemoEntity other = (DemoEntity) obj;
		if (aa01 == null) {
			if (other.aa01 != null)
				return false;
		} else if (!aa01.equals(other.aa01))
			return false;
		if (aa02 == null) {
			if (other.aa02 != null)
				return false;
		} else if (!aa02.equals(other.aa02))
			return false;
		if (aa03 == null) {
			if (other.aa03 != null)
				return false;
		} else if (!aa03.equals(other.aa03))
			return false;
		if (aa04 == null) {
			if (other.aa04 != null)
				return false;
		} else if (!aa04.equals(other.aa04))
			return false;
		if (aa05 == null) {
			if (other.aa05 != null)
				return false;
		} else if (!aa05.equals(other.aa05))
			return false;
		if (aa06 == null) {
			if (other.aa06 != null)
				return false;
		} else if (!aa06.equals(other.aa06))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "DemoEntity [aa01=" + aa01 + ", aa02=" + aa02 + ", aa03=" + aa03 + ", aa04=" + aa04 + ", aa05=" + aa05
				+ ", aa06=" + aa06 + "]";
	}

	
}

测试主方法:

package com.powersi.biz.collectinfo.mvc;

public class TestMain {
	public static void main(String[] args) {
		String[] arr = {"001","002","003","004","005","006"};
		DemoEntity demoEntity = new DemoEntity();
		DemoEntity castEntity = EntityUtils.castEntity(arr, DemoEntity.class, demoEntity);
		System.out.println(castEntity);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值