自动化立体仓库 - WMS系统
zhangchao
2024-11-23 04c5e6d5ad821cde0d32e48dc5557b4134b52e29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.zy.asrs.utils;
 
import com.core.common.DateUtils;
import lombok.SneakyThrows;
 
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.lang.reflect.Modifier;
 
public class EntityToMapConverter {
    @SneakyThrows
    public static Map<String, Object> entityToMapWithRandomValues(Object entity) {
        Map<String, Object> map = new HashMap<>();
        Field[] fields = entity.getClass().getDeclaredFields();
        Random random = new Random();
 
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                // Ignore static or final fields
                continue;
            }
            field.setAccessible(true);
            String fieldName = field.getName();
            Object fieldValue = field.get(entity);
 
            // Set random values based on type
            if (field.getType() == String.class) {
                map.put(fieldName, "'" + generateRandomString(10) + "'");
            } else if (field.getType() == Integer.class || field.getType() == int.class) {
                map.put(fieldName, random.nextInt(1000));
            } else if (field.getType() == Long.class || field.getType() == long.class) {
                map.put(fieldName, random.nextLong() % 1000L);
            } else if (field.getType() == Float.class || field.getType() == float.class) {
                map.put(fieldName, random.nextFloat() * 1000f);
            } else if (field.getType() == Double.class || field.getType() == double.class) {
                map.put(fieldName, random.nextDouble() * 1000d);
            } else if (field.getType() == Boolean.class || field.getType() == boolean.class) {
                map.put(fieldName, random.nextBoolean());
            } else if (field.getType() == BigDecimal.class) {
                map.put(fieldName, new BigDecimal(random.nextDouble() * 1000d));
            } else if (field.getType() == Date.class) {
                map.put(fieldName, "'" + DateUtils.convert(new Date()) + "'");
            } else {
                // For other types, you might want to handle them specifically or skip them
                continue;
            }
        }
        return map;
    }
 
    private static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(new Random().nextInt(characters.length())));
        }
        return sb.toString();
    }
}