I have several situations where a class consists of an arbitrary (but fixed) number of variables of differing types and wish to iterate over those variables as well as use their names in code. Is there a smarter way to do this than to retype each variable name in each function?
My initial thought is to use a HashMap to store the local variables but that seems inefficient and doesn’t handle multiple types.
Code below is simulated to shorten the required reading, but typically its more than 3 variables:
class Widget implements Parcelable {
String name, code;
Long price;
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(code);
dest.writeLong(price);
}
public Widget(Parcel o) {
name = o.name;
code = o.code;
price = o.price;
}
public String getXML() {
return "<Widget><name>"+name+"</name><code>"+code
+"</code><price>"+price+"</price></Widget>";
}
}
Instead, I’d prefer to do something like (pseudo-code):
public Widget(Parcel o) {
for (Map<Name,Data> item: o.getMap()) {
this.setValue(Name, Data);
}
}
public String getXML() {
StringBuilder XML = new StringBuilder();
XML.append("<Widget>");
for (Map<Name,Data> item: o.getMap()) {
XML.append("<"+Name+">" + Data + "</"+Name+">");
}
XML.append("</Widget>");
return XML.toString();
}
I keep thinking there must be a pattern for doing this type of thing, but maybe its just my Python history kicking at my Java experience.
Update: this is not about solely fetching XML from member variables, but about looping through member variables in multiple member functions. It would appear that Java’s reflection features were missing from my repertoire.
My new smaller constructor makes me glad to have learned something useful, and looks like:
public Widget(Widget other) {
for (Field f : getClass().getDeclaredFields()) {
if (f.getName() == "TAG") {
continue;
}
f.set(this, f.get(other));
}
}
That is usually solved with reflection:
However, for writing to / reading from XML, you probably want to use JAXB rather than reinventing the wheel.