Tuesday, 15 May 2012

reflection - get field value by its name in java -



reflection - get field value by its name in java -

i need read field value given field name. have class called product, has fields: size, image, link.. , have methods getsize(), getimage() , getlink() read values. if give 'size', want size calling getsize(), given 'image', image calling getimage()...

right have clumsy code phone call getfield(string fieldname) handler this:

public void string getfield(string fieldname, product p) { string value = ""; swtich(fieldname): case 'size': value = p.getsize(); break; case 'image': value = p.getimage(); break; ....

problem have many fields in class, whole code looks ugly. seek avoid reflection page because of poor readability. there other thought handle nicely? thanks

other reflection or explicit switch (as have), real alternative not have fields @ all. instead of getsize(), getimage(), etc., have general-purpose getattribute(attribute a). attribute there enum. like:

enum attribute { size, image, ... } public class product { map<attribute, string> attributes = new enummap<>(attribute.class); public string getattribute(attribute attribute) { homecoming attributes.get(attribute); } public void setattribute(attribute attribute, string value) { attributes.put(attribute, value); } ... }

enummaps efficient, code speedy -- not quite speedy real fields, not noticeably slower in app.

the reason making attribute enum (rather having string attribute keys, instance) gives same type safety explicit getter functions. instance, p.getattribute(attribute.not_a_real_attribute) produce compile-time error, same p.getnotarealattribute() (assuming enum value , method aren't defined, of course).

java reflection

No comments:

Post a Comment