All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commons.box.app.DataMap Maven / Gradle / Ivy

The newest version!
package commons.box.app;

import commons.box.app.bean.ClassAccess;
import commons.box.app.bean.ClassAccessField;
import commons.box.util.*;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 实现数据与map之间转换关系
 */
public interface DataMap {

    /**
     * 转换为 map data
     * 

* 如果在测试环节可以使用 DataMap.autoFieldsToMap() 方法(基于反射查找字段值并输出) * * @return */ public Map toMap(); /** * 转换为 map data *

* 默认基于反射进行操作,效率开销较大,只适用于 debug / test 环境 *

* 自行实现时,可以使用 transObject 方法来转换字段值 以便字段值涉及到 DataMap 实现 * * @return */ @Nonnull @SuppressWarnings("unchecked") public static Map autoFieldsToMap(DataMap object) { if (object == null) return null; Map map = new LinkedHashMap<>(); if (object instanceof Map) { Map mp = (Map) object; mp.forEach((k, v) -> map.put(Strs.toString(k), transObject(v))); } else { Class type = (Class) object.getClass(); ClassAccess ca = Beans.access(type); if (ca == null) return Maps.immmap(map); Map> cfs = ca.accessFields(); if (cfs != null) cfs.forEach((f, v) -> { try { Field ivf = Types.findField(type, f); if (ivf != null) { Types.makeAccessible(ivf); map.put(f, transObject((v == null) ? null : ivf.get(object))); } } catch (Throwable ignored) { } }); } return Maps.immmap(map); } /** * 转换 o 为 map *

* 如果 o 为 List / Set / Map,则依次对其内部对象进行转换 * * @param o * @return */ public static Object transObject(Object o) { if (o == null) return null; else if (o instanceof List) return transList((List) o); else if (o instanceof Set) return transSet((Set) o); else if (o instanceof Map) return transMap((Map) o); else if (o instanceof DataMap) return ((DataMap) o).toMap(); else return o; } /** * 转换 Map 中的 value,如果 value 实现了 toMap 则将其转换为 map 形式的 value * * @param map * @return */ public static Map transMap(Map map) { if (map == null) return null; Map rmap = new LinkedHashMap<>(); map.forEach((k, p) -> { if (k == null) return; rmap.put(k, transObject(p)); }); return Maps.immmap(rmap); } /** * 转换 List 中的 value,如果 value 实现了 toMap 则将其转换为 map 形式的 value * * @param list * @return */ public static List transList(List list) { if (list == null) return null; List rlist = new ArrayList<>(); list.forEach(e -> rlist.add(transObject(e))); return Collects.immlist(rlist); } /** * 转换 Set 中的 value,如果 value 实现了 toMap 则将其转换为 map 形式的 value * * @param set * @return */ public static Set transSet(Set set) { if (set == null) return null; Set rset = new LinkedHashSet<>(); set.forEach(e -> rset.add(transObject(e))); return Collects.immset(rset); } }