Java 如何在 Servlet 上下文中获取所有属性名称(是否嵌套)并迭代它是地图还是列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6613535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:16:21  来源:igfitidea点击:

How to get all attributes names(nested or not) in Servlet Context and iterate if it's a map or list?

javaloopsservletsattributes

提问by hamahama

I've tried to get attributeNames of a ill-maintained context, then use those names with reflection.

我试图获取维护不良的上下文的属性名称,然后通过反射使用这些名称。

Here's some pseudo code for a rough idea. E.g. I have an ArrayList and a HashMap in the context.

这是一些粗略的伪代码。例如,我在上下文中有一个 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
    }
}

采纳答案by Bohemian

Here's code that will do what you want:

这是可以执行您想要的操作的代码:

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);
        }
    }
}

Notes:

笔记:

  1. Always favour referring to the abstract interface over concrete implementations. In this case, check for Listand Map(interfaces), rather than ArrayListand HashMap(specific implementations); consider what will happen if the context hands you a LinkedListrather than an ArrayList, or a Mapthat's not a HashMap- your code would (unnecessarily) explode
  2. Use while (condition)rather than for (;condition;)- it's just ugly
  3. If you know the types of your Collections, specify them. For example, web contexts usually give you a Map<String, Object>:
  1. 始终倾向于引用抽象接口而不是具体实现。在这种情况下,检查ListMap(接口),而不是ArrayListHashMap(具体实现);考虑如果上下文给你 aLinkedList而不是ArrayList,或者Map不是 a会发生什么HashMap- 你的代码会(不必要地)爆炸
  2. 使用while (condition)而不是for (;condition;)- 它只是丑陋
  3. 如果您知道集合的类型,请指定它们。例如,网络上下文通常会给你一个Map<String, Object>

so the code could become

所以代码可以变成

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