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)
笔记:
List和Map(接口),而不是ArrayList和HashMap(具体实现); 考虑如果上下文给你一个LinkedList而不是一个ArrayList,或者一个Map不是一个HashMap- 你的代码会(不必要地)爆炸会发生什么while (condition)而不是for (;condition;)- 它只是丑陋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)
| 归档时间: |
|
| 查看次数: |
25872 次 |
| 最近记录: |