反射为pojo对象null值赋默认值

package com.cn.hzx.dataupload.core.utils;

import com.cn.hzx.dataupload.module.rsm.pojo.JTLLPojo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来判断对象属性元素是否为空
 * @Author ASUS
 * @Date 27/05/2022 15:45
 * @Version 1.0
 */
public class BlankUtils {

    /**
     * 普通对象JSON判空并为null值赋默认值
     *
     * @param obj
     * @return
     */
    private static Object initPropertyDefaultValue(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        Method[] methods = obj.getClass().getDeclaredMethods();
        Map<String, Method> methodNameMethodMap = new HashMap(methods.length);
        for (Method method : methods) {
            methodNameMethodMap.put(method.getName().toLowerCase(), method);
        }
        for (Field field : fields) {
            Class<?> clazz = field.getType();
            String propertyName = field.getName();
            try
            {
                String firstLetter = propertyName.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + propertyName.substring(1);
                Method method0 = obj.getClass().getMethod(getter, new Class[]{});
                Object value = method0.invoke(obj, new Object[]{});
                if (value != null) {
                    continue;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            Method method = methodNameMethodMap.get("set" + propertyName.toLowerCase());
            if (method == null) {
                continue;
            }
            try {
                if (isWrapClass(clazz) || isCommonDataType(clazz)) {
                    if (clazz == Boolean.class || clazz.getName().contains("boolean")) {
                        method.invoke(obj, Boolean.TRUE);
                    } else if (clazz == Byte.class || clazz.getName().contains("byte")) {
                        method.invoke(obj, new Byte("1"));
                    } else if (clazz == Short.class || clazz.getName().contains("short")) {
                        method.invoke(obj, new Short("1"));
                    } else if (clazz == Integer.class || clazz.getName().contains("int")) {
                        method.invoke(obj, 0);
                    } else if (clazz == Long.class || clazz.getName().contains("long")) {
                        method.invoke(obj, 0L);
                    } else if (clazz == Float.class || clazz.getName().contains("float")) {
                        method.invoke(obj, 0F);
                    } else if (clazz == Double.class || clazz.getName().contains("double")) {
                        method.invoke(obj, 0D);
                    } else if (clazz == Character.class || clazz.getName().contains("char")) {
                        method.invoke(obj, '0');
                    }
                } else if (BigDecimal.class.isAssignableFrom(clazz)) {
                    method.invoke(obj, new BigDecimal("1"));
                } else if (Date.class.isAssignableFrom(clazz)) {
                    method.invoke(obj, new Date());
                } else if (String.class.isAssignableFrom(clazz)) {
                    method.invoke(obj, "");
                } else if (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)) {
                    Type[] type = method.getGenericParameterTypes();
                    ParameterizedType pType = (ParameterizedType) type[0];
                    Collection collection = null;
                    if (pType.getRawType().toString().endsWith("List")) {
                        collection = Lists.newArrayList();
                    } else if (pType.getRawType().toString().endsWith("Set")) {
                        collection = Sets.newHashSet();
                    }
                    Object objValue = null;
                    try {
                        objValue = Class.forName(pType.getActualTypeArguments()[0].getTypeName()).newInstance();
                    } catch (Exception e) {
                    }
                    if (objValue == null) {
                        continue;
                    }
                    Object childObj = initPropertyDefaultValue(objValue);
                    collection.add(childObj);
                    method.invoke(obj, collection);
                } else {
                    method.invoke(obj, initPropertyDefaultValue(clazz.newInstance()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 判断是否是基础数据类型,即 int,double,long等类似格式
     */
    public static boolean isCommonDataType(Class clazz) {
        return clazz.isPrimitive();
    }

    /**
     * 判断是否是基础数据类型的包装类型
     *
     * @param clz
     * @return
     */
    public static boolean isWrapClass(Class clz) {
        try {
            return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false;
        }
    }

    //main方法测试
    public static void main(String[] args) {
        JTLLPojo info = new JTLLPojo();
        info.setPointNo("111111111");
        Object o = initPropertyDefaultValue(info);
        System.out.println(o.toString());
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值