反射赋值

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;


public class ReflectUtils {

    /**
     * 为一个对象的所有属性添加默认值
     * @param obj
     */
    public static void setDefaultValue(Object obj)
        throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        Class<?> objClass = obj.getClass();
        List<Field> declaredFields = new ArrayList<>();
        while (objClass != null){
            declaredFields.addAll(new ArrayList<>(Arrays.asList(objClass.getDeclaredFields())));
            objClass = objClass.getSuperclass();
        }

        for (Field field : declaredFields) {
            field.setAccessible(true);
            Object o = field.get(obj);
            if(o == null){
                // 属性类型
                Type genericType = field.getGenericType();
                String type = genericType.toString();

                switch (type){
                    case "class java.lang.String":
                        if(field.getName().toLowerCase().contains("datetime")){
                            field.set(obj, LocalDateTime.now().toString().replace("T"," "));
                        }else if(field.getName().toLowerCase().contains("date")){
                            field.set(obj, LocalDate.now().toString());
                        }else{
                            field.set(obj, RandomStringUtils.random(2,"uft-8"));
                        }
                        break;
                    case "class java.lang.Integer": field.set(obj, RandomUtils.nextInt(0,10));break;
                    case "class java.lang.Boolean": field.set(obj, false);break;
                    case "class java.lang.Long": field.set(obj,RandomUtils.nextLong(0,99));break;
                    case "class java.util.Date": field.set(obj,new Date());break;
                    default:
                        if(type.startsWith("class")){
                            String name = type.replace("class ", "");
                            Object o1 = Class.forName(name).newInstance();
                            setDefaultValue(o1);
                            field.set(obj,o1);
                        }else if(type.startsWith("java.util.List")){
                            List list = new ArrayList();
                            collectionSerDefaultValue(list,field);
                            field.set(obj,list);
                        }else if(type.startsWith("java.util.Set")){
                            Set set = new HashSet();
                            collectionSerDefaultValue(set,field);
                            field.set(obj,set);
                        }
                }
            }
        }
    }

    private static void collectionSerDefaultValue(Collection collection, Field field)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        // 属性类型
        Type genericType = field.getGenericType();
        ParameterizedType parameterizedType = (ParameterizedType)genericType;
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        if(actualTypeArguments != null){
            for (Type tempType : actualTypeArguments) {
                String name = tempType.toString().replace("class ", "");
                Class<?> clazz = Class.forName(name);
                Object temp;
                if(clazz.isEnum()){
                   Object[] values =  clazz.getEnumConstants();
                    temp=values[0];
                }else{
                    temp = clazz.newInstance();
                    setDefaultValue(temp);
                }
                collection.add(temp);
            }
        }

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北漂的菜小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值