场景:需要将一个对象的各个字段中的数据映射到另一个对象的字段数据中,或将一个数据库表映射到另一张表中。
本文使用泛型编程实现了一个对象映射功能的工具类。
需要源对象,映射关系map,目标类。由于是动态的类,所以使用Java的反射机制来获取字段名,填写字段数据。
除了一个映射工具类,还手动实现了一个类型转换工具类,保证在映射过程中的数据类型安全性。
数据映射工具类:DataMappingUtils .java
package com.xxxx.util;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class DataMappingUtils {// source:原始数据, fieldMap:映射关系(sourceField,targetField), targetClass:目标对象类型// 映射单个对象public static <T> T dataMapping(Map<String,Object> source, Map<String, String> fieldMap, Class<T> targetClass) {try {T target = targetClass.getDeclaredConstructor().newInstance();for (Map.Entry<String,String> entry : fieldMap.entrySet()) {String sourceField = entry.getKey();String targetField = entry.getValue();Object sourceValue = source.get(sourceField);if (sourceValue == null) continue;try {Field field = targetClass.getDeclaredField(targetField);field.setAccessible(true);Object convertedValue = TypeConvertUtils.convertValue(sourceValue,field.getType());field.set(target,convertedValue);} catch (NoSuchFieldException e) {throw new RuntimeException("目标对象不存在字段: " + targetField);}}return target;} catch (Exception e) {throw new RuntimeException("对象映射失败: " + e.getMessage(),e);}}// 批量映射public static <T> List<T> mapList(List<Map<String,Object>> sourceList, Map<String,String> fieldMap, Class<T> targetClass) {List<T> resultList = new ArrayList<>();for (Map<String, Object> sourceEntity : sourceList) {resultList.add(dataMapping(sourceEntity,fieldMap,targetClass));}return resultList;}
}
类型转换工具类(使用了阿里巴巴的fastjson依赖):TypeConvertUtils .java
package com.xxx.util;import com.alibaba.fastjson.JSON;import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;public class TypeConvertUtils {public static Object convertValue(Object value, Class<?> targetType) {if (value == null) {return null;}String stringValue = value.toString();if (targetType == String.class) {return stringValue;} else if (targetType == Integer.class || targetType == int.class) {return Integer.parseInt(stringValue);} else if (targetType == Double.class || targetType == double.class) {return Double.parseDouble(stringValue);} else if (targetType == Long.class || targetType == long.class) {return Long.parseLong(stringValue);} else if (targetType == Boolean.class || targetType == boolean.class) {return Boolean.parseBoolean(stringValue);} else if (targetType == Date.class) {try {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(stringValue);} catch (ParseException e) {throw new RuntimeException("日期格式错误: " + stringValue);}} else if (targetType == BigDecimal.class) {return new BigDecimal(stringValue);} else {// 如果字段是复杂对象,使用JSON反序列化 (fastjson依赖)return JSON.parseObject(stringValue, targetType);}}
}