I have a class for POJO with many fields like this:
class DataObj {
private String v1 = null;
private String v2 = null;
...
I want to take values for these fields from a map where keys names are related to fields names. The data
comes (from external device) in map like this:
V1=11
V2=22
...
So currently I'm defining a set of constants and use a switch to do this, like this:
private static final String V1 = "V1";
private static final String V2 = "V2";
...
DataObj(Map<String, String> data) {
for (String key : data.keySet()) {
String value = data.get(key);
switch (key) {
case V1:
v1 = value;
break;
case V2:
v2 = value;
break;
...
}
}
}
It seems to me like a very brute-force solution... Besides I have lots of these fields and they differ with single characters only so writing such switch block may be very error prone. Maybe someone could share a more clever mechanism (beside reflection) to solve such tasks?
EDIT - SELECTED SOLUTION
Using selected answer I've created a class:
abstract class PropertyMapper<T> {
private Map<String, Setter<T>> setters = new HashMap<>();
abstract void mapProperties();
public PropertyMapper() {
mapProperties();
}
protected void updateBean(Map<String, T> map) {
for (String key : map.keySet()) {
setField(key, map.get(key));
}
}
protected void mapProperty(String property, Setter<T> fieldAssignment) {
setters.put(property, fieldAssignment);
}
protected interface Setter<T> { void set(T o); }
private void setField(String s, T o) { setters.get(s).set(o); }
}
And then I simply override mapProperties
method.
class DataObj extends PropertyMapper<String> {
private String v1 = null;
private String v2 = null;
...
DataObj(Map<String, String> data) {
updateBean(data);
}
@Override
void mapProperties() {
mapProperty("V1", o -> v1 = o);
mapProperty("V2", o -> v2 = o);
...
}
}
And this is something I was looking for - a clever mechanism resulting in concise property-to-field mapping code.