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



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

i've tried attributenames of ill-maintained context, utilize names reflection.

here's pseudo code rough idea. e.g. have arraylist , hashmap in context.

enum = getservletcontext().getattributenames(); (; enum.hasmoreelements(); ) { string name = (string)enum.nextelement(); // value of attribute object value = getservletcontext().getattribute(name); if (value instanceof hashmap){ hashmap hmap = (hashmap) value; //iterate , print key value pair here }else if(value instanceof arraylist){ //do arraylist iterate here , print } }

here's code want:

enumeration<?> e = getservletcontext().getattributenames(); while (e.hasmoreelements()) { string name = (string) e.nextelement(); // value of attribute object value = getservletcontext().getattribute(name); if (value instanceof map) { (map.entry<?, ?> entry : ((map<?, ?>)value).entryset()) { system.out.println(entry.getkey() + "=" + entry.getvalue()); } } else if (value instanceof list) { (object element : (list)value) { system.out.println(element); } } }

notes:

always favour referring abstract interface on concrete implementations. in case, check list , map (interfaces), rather arraylist , hashmap (specific implementations); consider happen if context hands linkedlist rather arraylist, or map that's not hashmap - code (unnecessarily) explode use while (condition) rather for (;condition;) - it's ugly if know types of collections, specify them. example, web contexts give map<string, object>:

so code become

for (map.entry<string, object> entry : ((map<string, object>)value).entryset()) { string entrykey = entry.getkey(); object entryvalue = entry.getvalue(); }

java loops servlets attributes

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -