Reputation: 5031
i need to read the field value given the field name. say i have class called product, it has fields: size, image, link.. and have methods as getSize(), getImage() and getLink() to read those values. now if i give 'size', i want to get size by calling getSize(), given 'image', get image by calling getImage()...
right now i have a clumsy code call getField(String fieldName) to 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 is i have too many fields in this class, the whole code looks ugly. also i try to avoid the reflection page because of the poor readability. is there any other idea to handle this nicely? thanks
Upvotes: 0
Views: 388
Reputation: 76
You may consider to use directly attribute names as keys of map and values as attributes.
HashMap<String, Object> attributes
Thus you don't have to modify your structure or enum if new attributes are added.
Beware, "Size" and "size" will be behaved differently.
Upvotes: 0
Reputation: 43391
Other than reflection or an explicit switch (as you have), the only real alternative is to not have those fields at all. Instead of getSize()
, getImage()
, etc., you could just have a general-purpose getAttribute(Attribute a)
. Attribute
there would probably be an enum
. Something like:
enum Attribute { SIZE, IMAGE, ... }
public class Product {
Map<Attribute, String> attributes = new EnumMap<>(Attribute.class);
public String getAttribute(Attribute attribute) {
return attributes.get(attribute);
}
public void setAttribute(Attribute attribute, String value) {
attributes.put(attribute, value);
}
...
}
EnumMap
s are very efficient, so this code will be speedy -- not quite as speedy as real fields, but probably not noticeably slower in your app.
The reason for making Attribute
an enum
(rather than just having String
attribute keys, for instance) is that it gives you the same type safety as explicit getter functions. For instance, p.getAttribute(Attribute.NOT_A_REAL_ATTRIBUTE)
will produce a compile-time error, same as p.getNotARealAttribute()
would (assuming that enum value and method aren't defined, of course).
Upvotes: 1