Java 通过反射给 null值的字段属性 批量赋值

工具类:

DefaultValueUtil.java 
 

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.*;



public class DefaultValueUtil {

    /**
     * 給为null的字段赋默认值
     *
     * @param obj
     * @return
     */
    private static Object setDefaultValue(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) || clazz.isPrimitive()) {
                    if (clazz == Boolean.class || clazz.getName().contains("boolean")) {
                        method.invoke(obj, Boolean.FALSE);
                    } else if (clazz == Byte.class || clazz.getName().contains("byte")) {
                        method.invoke(obj, new Byte("0"));
                    } else if (clazz == Short.class || clazz.getName().contains("short")) {
                        method.invoke(obj, new Short("0"));
                    } 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, BigDecimal.ZERO);
                } 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 = setDefaultValue(objValue);
                    collection.add(childObj);
                    method.invoke(obj, collection);
                } else {
                    method.invoke(obj, setDefaultValue(clazz.newInstance()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    public static boolean isWrapClass(Class clz) {
        try {
            return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        TestDTO dto = new TestDTO();
        dto.setTAmount(new BigDecimal("999"));
        dto.setRemark("点赞收藏");
        System.out.println("前:" + dto.toString());
        Object o = setDefaultValue(dto);
        System.out.println("后:" + o.toString());
    }


}

效果:

 

注意点:

什么时候需要使用 这种反射赋值的场景, 大家也是需要有取舍有考虑


好了,该篇就到这。

猜你喜欢

转载自blog.csdn.net/qq_35387940/article/details/129498725