com.yixan.tools.common.model.DepthPathMap Maven / Gradle / Ivy
package com.yixan.tools.common.model;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* 深度路径Map, 用于Ognl取值
* a.b.c, a.b.c.d 不能共存, 保留最路径最深的a.b.c.d
*
*
* DepthPathMap dpm = new DepthPathMap();
* dpm.put("author", "xxx"); // 该设置无效, 会被后面的覆盖掉
* dpm.put("author.code", 100);
* dpm.put("author.name", "zhaohuihua");
*
* dpm.put("code.folder.service", "service");
* dpm.put("code.folder.page", "views");
* dpm.put("code.folder", "java"); // 该设置无效, 会被忽略掉
*
* Map map = dpm.map();
*
* Ognl.getValue("author", map); -- Map({code=100, name=zhaohuihua})
* Ognl.getValue("author.code", map); -- 100
* Ognl.getValue("author.name", map); -- zhaohuihua
*
* Ognl.getValue("code.folder", map); -- Map({service=service, page=views})
* Ognl.getValue("code.folder.service", map); -- service
* Ognl.getValue("code.folder.page", map); -- views
*
*
* @author zhaohuihua
* @version V1.0 2015年12月21日
*/
public class DepthPathMap {
private static final Pattern SEPARATOR = Pattern.compile("\\.");
private Map map = new HashMap<>();
@SuppressWarnings("unchecked")
public DepthPathMap put(String key, Object value) {
String[] keys = SEPARATOR.split(key);
List list = Arrays.asList(keys);
Iterator iterator = list.iterator();
Map parent = map;
while (iterator.hasNext()) {
String name = iterator.next();
Object older = parent.get(name);
if (iterator.hasNext()) {
// 有下一级
if (older == null || !(older instanceof Map)) {
// !(older instanceof Map):
// 如果之前有a.b.c, 新加一个a.b.c.d, 覆盖掉a.b.c
older = new HashMap<>();
parent.put(name, older);
}
} else {
// 没有下一级
if (older != null && older instanceof Map) {
// 如果之前有a.b.c.d, 新加一个a.b.c, 忽略a.b.c
continue;
}
parent.put(name, value);
}
parent = (Map) older;
}
return this;
}
public Map map() {
return map;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy