下面的方法获取一个“Route”(类名和类方法):
public Route getRoute(final String method, final String request) {
if (hasRoutes) {
for (Map.Entry<Pattern, HashMap<String, String>> entry : routes) {
Matcher match = entry.getKey().matcher(request);
if (match.find()) {
HashMap<String, String> methods = entry.getValue();
// ISSUE: Returns FALSE after 1st call of Router.getRoute()
if (methods.containsKey(method)) {
return new Route(match.group("interface"), "TRUE (" + method + " - " + match.group("interface") + "): " + methods.get(method));
} else {
return new Route(match.group("interface"), "FALSE (" + method + " - " + match.group("interface") + "): " + methods.values().toString() + ", SIZE: " + entry.getValue().size());
}
//return entry.getValue().containsKey(method) ? new Route(match.group("interface"), entry.getValue().get(method)) : null;
}
}
}
return null;
}
“路线”定义为:
private Set<Entry<Pattern, HashMap<String, String>>> routes;
它是定义支持路由的 JSON 配置文件的缓存表示,例如:
{
"^/?(?<interface>threads)/?$": {
"GET": "list",
"POST": "create"
},
"^/?(?<interface>threads)/(?<id>\\d+)/?$": {
"GET": "get",
"POST": "reply",
"PUT": "edit",
"PATCH": "edit",
"DELETE": "delete"
}
}
编辑,这里是如何从 JSON 文件的内容中填充“路由”:
try {
JsonParser parser = JSONFactory.createJsonParser(in);
JsonNode root = JSONMapper.readTree(parser);
Iterator base = root.getFieldNames();
Iterator node;
String match, method;
HashMap<Pattern, HashMap<String, String>> routesMap = new HashMap();
while (base.hasNext()) {
match = base.next().toString();
if (match != null) {
node = root.get(match).getFieldNames();
HashMap<String, String> methods = new HashMap();
while (node.hasNext()) {
method = node.next().toString();
if (method != null) {
methods.put(method, root.get(match).get(method).getTextValue());
}
}
if (!methods.isEmpty()) {
routesMap.put(Pattern.compile(match), methods);
}
}
}
if (!routesMap.isEmpty()) {
hasRoutes = true;
routes = routesMap.entrySet();
}
// Help garbage collection
parser = null;
root = null;
base = null;
node = null;
match = null;
method = null;
routesMap = null;
} catch (Exception ex) {
}
编辑 2,有问题的属性和 init() 方法:
public final static JsonFactory JSONFactory = new JsonFactory();
public final static ObjectMapper JSONMapper = new ObjectMapper();
public static Router router;
private final Class self = getClass();
private final ClassLoader loader = self.getClassLoader();
public void init(ServletConfig config) throws ServletException {
super.init(config);
router = new Router(self.getResourceAsStream("/v1_0/Routes.json"), JSONFactory, JSONMapper);
}
由于某种原因,在第一次访问 servlet 后,HashMap 中没有值。 x.size() 返回零。
这是从头开始重写 PHP 应用程序,所以如果问题很普通,我提前表示歉意。
完整来源: - Router source - Route source
最佳答案
您的 getOptions()
方法会在迭代时从此映射中删除每个条目。因此,调用一次 getOptions()
后, map 为空。
顺便说一句,将null
赋值给变量不会“帮助垃圾收集器”。垃圾收集器知道当退出变量的范围时,该变量不再引用该对象。您实际上是通过分配永远无法读取的值 (null
) 来减慢速度(以及用适得其反的噪音使您的代码困惑)。 FindBugs 等优秀的静态分析工具会警告您这是错误的代码。
关于java - 遍历 HashSet 清空 HashMap 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8657633/