Here is the 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 prefer to refer to an abstract interface over specific implementations. In this case, check
List and Map (interfaces), not ArrayList and HashMap (specific implementations); consider what happens if the context passes you a LinkedList , not an ArrayList or Map , not a HashMap - your code (without need) will explode - Use
while (condition) , not for (;condition;) - it's just ugly - If you know the types of your Collections, list them. For example, web contexts usually provide you with
Map<String, Object> :
so the code can become
for (Map.Entry<String, Object> entry : ((Map<String, Object>)value).entrySet()) { String entryKey = entry.getKey(); Object entryValue = entry.getValue(); }
source share