自学内容网 自学内容网

JAVA通过实体类注解生成测试数据

注解

package cn.ac.iscas.utils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 注解用于生成测试数据
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ValueRange {
    double min() default Double.MIN_VALUE;//生成最小值
    double max() default Double.MAX_VALUE;//生成最大值
    int decimalPlaces() default 0; // 小数点后的位数,默认为0
}

工具类

package cn.ac.iscas.utils;

import cn.ac.iscas.entity.topic2.NearshoreBuoyMonitoringADCP;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Random;

/**
 * 根据实体类配置ValueRange注解的最大值最小值生成测试数据
 */
public class DataGeneratorUtils {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        System.out.println(generateTestData(NearshoreBuoyMonitoringADCP.class));
    }

    private static final Random random = new Random();
    private static final int DEFAULT_STRING_LENGTH = 10;
    private static final int DEFAULT_NUMBER_DIGITS = 5; // 默认生成数字的位数

    public static <T> T generateTestData(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T instance = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true); // 设置字段可访问
            Class<?> fieldType = field.getType();
            if (field.isAnnotationPresent(ValueRange.class)) {
                ValueRange range = field.getAnnotation(ValueRange.class);
                if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                    field.set(instance, generateRandomIntInRange(range.min(), range.max()));
                } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                    field.set(instance, generateRandomLongInRange(range.min(), range.max()));
                } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                    field.set(instance, generateRandomFloatInRange(range.min(), range.max(),range.decimalPlaces()));
                } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                    field.set(instance, generateRandomDoubleInRange(range.min(), range.max(),range.decimalPlaces()));
                } // 可根据需要扩展其他类型的数据生成
            } else {
                // 如果没有注解,则正常生成数据
                if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                    field.set(instance, generateRandomInt());
                } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                    field.set(instance, generateRandomLong());
                } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                    field.set(instance, generateRandomFloat());
                } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                    field.set(instance, generateRandomDouble());
                } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                    field.set(instance, random.nextBoolean());
                } else if (fieldType.equals(String.class)) {
                    field.set(instance, generateRandomString(DEFAULT_STRING_LENGTH));
                } else if (fieldType.equals(Date.class)) {
                    field.set(instance, generateRandomDate());
                } // 可根据需要扩展其他类型的数据生成
            }
        }
        return instance;
    }

    private static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            char c = (char) (random.nextInt(26) + 'a');
            sb.append(c);
        }
        return sb.toString();
    }

    private static int generateRandomInt() {
        int min = (int) Math.pow(10, DEFAULT_NUMBER_DIGITS - 1);
        int max = (int) Math.pow(10, DEFAULT_NUMBER_DIGITS) - 1;
        return random.nextInt(max - min + 1) + min;
    }

    private static long generateRandomLong() {
        long min = (long) Math.pow(10, DEFAULT_NUMBER_DIGITS - 1);
        long max = (long) Math.pow(10, DEFAULT_NUMBER_DIGITS) - 1;
        return min + ((long) (random.nextDouble() * (max - min)));
    }

    private static float generateRandomFloat() {
        float min = (float) Math.pow(10, -DEFAULT_NUMBER_DIGITS);
        float max = (float) Math.pow(10, DEFAULT_NUMBER_DIGITS);
        return min + random.nextFloat() * (max - min);
    }

    private static double generateRandomDouble() {
        double min = Math.pow(10, -DEFAULT_NUMBER_DIGITS);
        double max = Math.pow(10, DEFAULT_NUMBER_DIGITS);
        return min + random.nextDouble() * (max - min);
    }

    private static Date generateRandomDate() {
        long currentTimeMillis = System.currentTimeMillis();
        long randomTimeMillis = random.nextLong() % currentTimeMillis;
        return new Date(randomTimeMillis);
    }

    private static int generateRandomIntInRange(double min, double max) {
        return (int) (min + random.nextDouble() * (max - min));
    }

    private static long generateRandomLongInRange(double min, double max) {
        return (long) (min + random.nextDouble() * (max - min));
    }

    private static double roundToDecimalPlaces(double value, int decimalPlaces) {
        double factor = Math.pow(10, decimalPlaces);
        return Math.round(value * factor) / factor;
    }

    private static float roundToDecimalPlaces(float value, int decimalPlaces) {
        float factor = (float) Math.pow(10, decimalPlaces);
        return Math.round(value * factor) / factor;
    }

    // 在生成随机数时使用 roundToDecimalPlaces 方法进行处理
    private static float generateRandomFloatInRange(double min, double max, int decimalPlaces) {
        float value = (float) (min + random.nextDouble() * (max - min));
        return roundToDecimalPlaces(value, decimalPlaces);
    }

    private static double generateRandomDoubleInRange(double min, double max, int decimalPlaces) {
        double value = min + random.nextDouble() * (max - min);
        return roundToDecimalPlaces(value, decimalPlaces);
    }
}

示例实体类

public class NearshoreBuoyMonitoringCO2 {
    private String _id;
    @DSColumnComment("时间")
    private Date time;

    @DSColumnComment("水中CO2(ppb)")
    @ValueRange(min = 0, max = 3000, decimalPlaces = 2)
    private Double co2InWater;

    @DSColumnComment("空气中CO2(ppb)")
    @ValueRange(min = 0, max = 3000, decimalPlaces = 2)
    private Double co2InAir;
}

原文地址:https://blog.csdn.net/wenyichuan/article/details/140706840

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!