|
|
|
@ -1,5 +1,6 @@ |
|
|
|
|
package org.energy.modules.system.util; |
|
|
|
|
|
|
|
|
|
import java.lang.reflect.Field; |
|
|
|
|
import java.util.Map; |
|
|
|
|
import java.util.function.Supplier; |
|
|
|
|
|
|
|
|
@ -7,16 +8,64 @@ public class DataUtils { |
|
|
|
|
|
|
|
|
|
public static <T> T mapToEntity(Map<String, Object> map, Supplier<T> supplier) { |
|
|
|
|
T entity = supplier.get(); |
|
|
|
|
Class<?> clazz = entity.getClass(); |
|
|
|
|
|
|
|
|
|
map.forEach((key, value) -> { |
|
|
|
|
try { |
|
|
|
|
entity.getClass().getDeclaredField(key).setAccessible(true); |
|
|
|
|
entity.getClass().getDeclaredField(key).set(entity, value); |
|
|
|
|
} catch (NoSuchFieldException | IllegalAccessException e) { |
|
|
|
|
Field field = findField(clazz, key); |
|
|
|
|
if (field != null) { |
|
|
|
|
field.setAccessible(true); |
|
|
|
|
Object castedValue = castValue(field.getType(), value); |
|
|
|
|
field.set(entity, castedValue); |
|
|
|
|
} else { |
|
|
|
|
System.err.println("Field not found: " + key); |
|
|
|
|
} |
|
|
|
|
} catch (IllegalAccessException e) { |
|
|
|
|
System.err.println("IllegalAccessException for field: " + key); |
|
|
|
|
e.printStackTrace(); |
|
|
|
|
} catch (Exception e) { |
|
|
|
|
System.err.println("Unexpected exception for field: " + key); |
|
|
|
|
e.printStackTrace(); |
|
|
|
|
} |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
return entity; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
private static Field findField(Class<?> clazz, String fieldName) { |
|
|
|
|
while (clazz != null) { |
|
|
|
|
try { |
|
|
|
|
return clazz.getDeclaredField(fieldName); |
|
|
|
|
} catch (NoSuchFieldException e) { |
|
|
|
|
clazz = clazz.getSuperclass(); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
return null; // Field not found
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
private static Object castValue(Class<?> fieldType, Object value) { |
|
|
|
|
if (value == null) { |
|
|
|
|
return null; |
|
|
|
|
} |
|
|
|
|
if (fieldType.isAssignableFrom(value.getClass())) { |
|
|
|
|
return value; |
|
|
|
|
} |
|
|
|
|
if (fieldType == int.class || fieldType == Integer.class) { |
|
|
|
|
return Integer.parseInt(value.toString()); |
|
|
|
|
} |
|
|
|
|
if (fieldType == long.class || fieldType == Long.class) { |
|
|
|
|
return Long.parseLong(value.toString()); |
|
|
|
|
} |
|
|
|
|
if (fieldType == float.class || fieldType == Float.class) { |
|
|
|
|
return Float.parseFloat(value.toString()); |
|
|
|
|
} |
|
|
|
|
if (fieldType == double.class || fieldType == Double.class) { |
|
|
|
|
return Double.parseDouble(value.toString()); |
|
|
|
|
} |
|
|
|
|
if (fieldType == boolean.class || fieldType == Boolean.class) { |
|
|
|
|
return Boolean.parseBoolean(value.toString()); |
|
|
|
|
} |
|
|
|
|
// Add more type conversions as needed
|
|
|
|
|
return value; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|