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();
|
}
|
}
|