如何获取Servlet Context中的所有属性名称(嵌套与否),如果是映射或列表则迭代?

ham*_*ama 7 java attributes loops servlets

我试图获取一个维护不良的上下文的attributeNames,然后使用带有反射的那些名称.

这是一些粗略思想的伪代码.例如,我在上下文中有一个ArrayList和一个HashMap.

enum = getServletContext().getAttributeNames();
for (; enum.hasMoreElements(); ) {
    String name = (String)enum.nextElement();

    // Get the value of the attribute
    Object value = getServletContext().getAttribute(name);

    if (value instanceof HashMap){
      HashMap hmap = (HashMap) value;
      //iterate and print key value pair here
    }else if(value instanceof ArrayList){
      //do arraylist iterate here and print
    }
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 11

这里的代码可以满足您的需求:

Enumeration<?> e = getServletContext().getAttributeNames();
while (e.hasMoreElements())
{
    String name = (String) e.nextElement();

    // Get the value of the attribute
    Object value = getServletContext().getAttribute(name);

    if (value instanceof Map) {
        for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    } else if (value instanceof List) {
        for (Object element : (List)value) {
            System.out.println(element);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 总是倾向于通过具体实现来引用抽象接口.在这种情况下,检查ListMap(接口),而不是ArrayListHashMap(具体实现); 考虑如果上下文给你一个LinkedList而不是一个ArrayList,或者一个Map不是一个HashMap- 你的代码会(不必要地)爆炸会发生什么
  2. 使用while (condition)而不是for (;condition;)- 它只是丑陋
  3. 如果您知道集合的类型,请指定它们.例如,Web上下文通常会给你一个Map<String, Object>:

所以代码可以成为

for (Map.Entry<String, Object> entry : ((Map<String, Object>)value).entrySet()) {
    String entryKey = entry.getKey();
    Object entryValue = entry.getValue();
}
Run Code Online (Sandbox Code Playgroud)