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
How to get all attributes names(nested or not) in Servlet Context and iterate if it's a map or list?
提问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:
笔记:
- Always favour referring to the abstract interface over concrete implementations. In this case, check for
List
andMap
(interfaces), rather thanArrayList
andHashMap
(specific implementations); consider what will happen if the context hands you aLinkedList
rather than anArrayList
, or aMap
that's not aHashMap
- your code would (unnecessarily) explode - Use
while (condition)
rather thanfor (;condition;)
- it's just ugly - If you know the types of your Collections, specify them. For example, web contexts usually give you a
Map<String, Object>
:
- 始终倾向于引用抽象接口而不是具体实现。在这种情况下,检查
List
和Map
(接口),而不是ArrayList
和HashMap
(具体实现);考虑如果上下文给你 aLinkedList
而不是ArrayList
,或者Map
不是 a会发生什么HashMap
- 你的代码会(不必要地)爆炸 - 使用
while (condition)
而不是for (;condition;)
- 它只是丑陋 - 如果您知道集合的类型,请指定它们。例如,网络上下文通常会给你一个
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();
}