ObjUtil.java 2.56 KB
Newer Older
谢恒's avatar
谢恒 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
package com.hs.admin.util;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author:XIEHENG
 * @Date: 2018/8/6
 * @Time:9:32
 */
public class ObjUtil {

    /**
     * 获取对象下所有不为空的属性和值
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> checkfield(Object obj) {
        Map<String, Object> map = null;
        try {
            Class<?> objClass = obj.getClass();
            Field[] fields = objClass.getDeclaredFields();
            map = new HashMap<>();
            for (Field field : fields) {
                field.setAccessible(true);
                Object val = field.get(obj);
                if (val != null) {
                    map.put(field.getName(), val);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void initField(Object object) {
        try {
            Class<?> objectClass = object.getClass();
            Field[] fields = objectClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String type = field.getType().getSimpleName();
                if (field.get(object) == null) {
                    if (type.equals("String")) {
                        field.set(object, "");
                    } else if (type.equals("Integer")) {
                        field.set(object, new Integer(0));
                    } else if (type.equals("Long")) {
                        field.set(object, new Long(0));
                    } else if (type.equals("Char")) {
                        field.set(object, "");
                    } else if (type.equals("Date")) {
                        field.set(object, new Date());
                    } else if (type.equals("BigDecimal")) {
                        field.set(object, new BigDecimal(0));
                    } else if (type.equals("Double")) {
                        field.set(object, new Double(0));
                    } else if (type.equals("Byte")) {
                        field.set(object, new Byte("0"));
                    } else if (type.equals("Float")) {
                        field.set(object, new Float(0));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}