
com.moon.core.util.MapperUtil Maven / Gradle / Ivy
package com.moon.core.util;
import com.moon.core.beans.BeanInfoUtil;
import com.moon.core.lang.ThrowUtil;
import com.moon.core.lang.reflect.ConstructorUtil;
import com.moon.core.util.converter.TypeCaster;
import java.util.*;
import static com.moon.core.beans.BeanInfoUtil.getFieldDescriptorsMap;
import static com.moon.core.lang.ThrowUtil.noInstanceError;
import static com.moon.core.lang.reflect.ConstructorUtil.newInstance;
/**
* 映射器:提供实体到 Map,实体到另一个实体,实体到类,Map 到实体之间的映射
*
* @author moonsky
* @see com.moon.core.sql.ResultSetUtil 提供 SQL 查询结果集到实体、数组、Map 的映射
*/
public final class MapperUtil {
private MapperUtil() { noInstanceError(); }
/*
* ---------------------------------------------------------------------------
* mapper
* ---------------------------------------------------------------------------
*/
public static Map toMap(Object bean) { return toMap(bean, new HashMap(16)); }
public static Map toMap(Object bean, Map result) {
if (bean != null) {
getFieldDescriptorsMap(bean.getClass()).forEach((name, d) ->
result.put(name, d.getValueIfPresent(bean, true)));
}
return result;
}
public static T toInstance(Map data, Class type) {
return overrideImpl(data, newInstance(type, true), type);
}
public static T toInstance(E data, Class type) {
return override(data, newInstance(type, true));
}
public static T override(Map data, T bean) {
return overrideImpl(data, bean, (Class) bean.getClass());
}
public static E override(T t, E e) {
final Class targetType = e.getClass();
getFieldDescriptorsMap(t.getClass()).forEach((name, srcDesc) -> {
BeanInfoUtil.ifSetterExecutorPresent(targetType, name, setDesc -> {
setDesc.setValue(e, srcDesc.getValue(t, true), true);
});
});
return e;
}
/*
* ---------------------------------------------------------------------------
* for each mapper
* ---------------------------------------------------------------------------
*/
public static List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy