Map深层次对象获取工具
此工具根据spel表达式,从嵌套Map中获取值,可以简化代码
同时提供了Map链式创建的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| public class MapUtil {
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
public static <T> T getValue(Map map,String name,Class<T> clazz){ EvaluationContext ctx = mapEvaluationContext(map); String spel = convertSpel(name); Object value = PARSER.parseExpression("#map" + spel).getValue(ctx); if (value instanceof String){ if (clazz != String.class){ throw new ClassCastException(); } return (T)value; } return BeanUtil.toBean(value, clazz); }
public static void setValue(Map map,String name,Object value){ EvaluationContext context = mapEvaluationContext(map); String spel = convertSpel(name); PARSER.parseExpression("#map" + spel).setValue(context, value); } private static EvaluationContext mapEvaluationContext(Map map){ EvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("map",map); return ctx; } private static String convertSpel(String name){ String[] split = name.split("\\."); StringBuilder builder = new StringBuilder(""); for (String s : split) { builder.append("['").append(s).append("']"); } return builder.toString(); }
public static <K, V> Builder<K, V> builder(Class<K> keyClass,Class<V> valueCLass){ return new Builder<K, V>(keyClass,valueCLass); } public static <K, V> Builder<K, V> builder(){ return new Builder<K, V>(); }
public static class Builder<K,V> { private final Map<K, V> map; private Builder(Class<K> keyClass,Class<V> valueCLass) { map = new HashMap<K,V>(); } private Builder() { map = new HashMap<K,V>(); } public Builder<K,V> put(K k,V v){ map.put(k, v); return this; } public Map<K,V> build(){ return map; } }
|