reflection - Dynamic attribute lookup in java -


python has way dynamically find , retrieve object attribute using hasattr , getarr:

try:     if hasattr(obj,name)       thing = getattr(obj, name)   except attributeerror:     pass   else:     break 

what efficient(coding , performance) way achieve java?
serializing instances of class - , on time ,attributes may added class.
so,on retrieval,i should able hand out getattribute-styled api client - , return attribute if particular version supports it.

the best way using reflection field, make accessible (in case it's private or otherwise not accessible current scope), , value relation object in question.

public static object getattribute(object obj, string name) throws exception {     field field = obj.getclass().getdeclaredfield(name);     field.setaccessible(true);     return field.get(obj); } 

a nosuchfieldexception thrown in event no field exists called name.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -