randomObject 根据类随机生成对象

  • 自动生成的时候用了 hutoolcommons-lang3 ,这个可以用 java 原生的 random 生成
		<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8</version>
        </dependency>
        
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.5</version>
        </dependency>
  • 运用 java 反射 实现对象的创建和属性的赋值
public class Util {

    /**
     * 根据类名 创建一个随机生成对象
     */
    public static Object randomObject(Class<?> clazz) {
        return randomObject_(clazz, new ArrayList<Class>());
    }

    /**
     * 动态生成
     *
     * @param clazz  要生成的类
     * @param hasClz 记录已经生成过的类,为了避免递归死循环
     * @return
     */
    private static Object randomObject_(Class<?> clazz, final List<Class> hasClz) {
        Class sourceClass = clazz;
        Object obj = null;
        try {
            obj = clazz.newInstance();
            //获取对象所有字段 包括父类
            ArrayList<Field> fields = new ArrayList<>();
            while (sourceClass != null) {
                fields.addAll(Arrays.asList(sourceClass.getDeclaredFields()));
                sourceClass = sourceClass.getSuperclass();
            }
            for (Field field : fields) {
                //todo:通过自定义注解去筛掉哪些需要自动赋值,哪些不需要
                //https://blog.csdn.net/qq_36666651/article/details/81215221
                Class<?> type = parseClassType(field.getType());
                field.setAccessible(true);
                if (String.class == type) {
                    field.set(obj, RandomUtil.randomString(5));
                } else if (Date.class == type) {
                    field.set(obj, randomDateTime());
                } else if (type.isPrimitive()) {
                    if (boolean.class == type) {
                        field.set(obj, RandomUtil.randomBoolean());
                    } else if (char.class == type) {
                        field.set(obj, RandomUtil.randomChar());
                    } else if (byte.class == type) {
                        field.set(obj, RandomUtil.randomBytes(1)[0]);
                    } else if (short.class == type) {
                        short ashort = (short) (RandomUtil.randomInt(0, 99999) & 0x7FFF);
                        field.set(obj, ashort);
                    } else if (int.class == type) {
                        field.set(obj, RandomUtil.randomInt(0, 99999));
                    } else if (long.class == type) {
                        field.set(obj, RandomUtil.randomLong(0, 9999));
                    } else if (float.class == type) {
                        field.set(obj, RandomUtils.nextFloat(100, 9999));
                    } else if (double.class == type) {
                        field.set(obj, RandomUtil.randomDouble(10, 99999, 2, RoundingMode.DOWN));
                    }
                } else if (hasClz.contains(type)) {
                    //已经生成过了,再次生成就陷入了递归循环
                    field.set(obj, null);
                } else {
                    //以上类型都不是,就递归生成
                    hasClz.add(type);
                    field.set(obj, randomObject_(type, hasClz));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    private static Date randomDateTime() {
        String beginDate = "1900-01-01";
        String endDate = "2020-01-01";
        return randomDate(beginDate, endDate);
    }

    /**
     * 随机生成日期
     *
     * @param beginDate 开始日期
     * @param endDate   结束日期
     * @return
     */
    public static Date randomDate(String beginDate, String endDate) {
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(beginDate);
            Date end = format.parse(endDate);
            if (start.getTime() >= end.getTime()) {
                return new Date();
            }
            long date = random(start.getTime(), end.getTime());
            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }

    /**
     * 将基础类和包装类相对应
     * java.lang.Boolean#TYPE == boolean
     * java.lang.Character#TYPE == character
     * java.lang.Byte#TYPE == byte
     * java.lang.Short#TYPE == short
     * java.lang.Integer#TYPE == integer
     * java.lang.Long#TYPE == long
     * java.lang.Float#TYPE == float
     * java.lang.Double#TYPE == double
     * java.lang.Void#TYPE == void
     */
    private static Class<?> parseClassType(Class<?> type) {
        final Map<Class, Class> classes = new HashMap<>(9);
        classes.put(Boolean.class, boolean.class);
        classes.put(Character.class, char.class);
        classes.put(Byte.class, byte.class);
        classes.put(Short.class, short.class);
        classes.put(Integer.class, int.class);
        classes.put(Long.class, long.class);
        classes.put(Float.class, float.class);
        classes.put(Double.class, double.class);
        return classes.getOrDefault(type, type);
    }

参考:org.hibernate.query.spi.QueryParameterBindingValidator

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章