I need to update several POJO fields according to a map which holds only the changes.
For example (loosely coded) :
Class MyClass{
public MyClass(a,b,c);
private int a;
private int b;
private int c;
}
int main(){
Map<String, String> keyValueMap = new HashMap<>();
MyClass obj = new MyClass(1,2,3);
keyValueMap.put("c", 6);
keyValueMap.put("b", 4);
//Update only b and c values of obj:
updateObj(obj, keyValueMap);
keyValueMap.put("a", 5);
keyValueMap.put("b", 7);
//Update only a and b values of obj:
updateObj(obj, keyValueMap);
}
void updateObj(MyClass obj, Map<String, String> keyValueMap){
for (Map.Entry<String,String> entry : keyValueMap.entrySet())
if(entry.getKey().equals("a")
obj.setA(entry.getValue();
if(entry.getKey().equals("b")
obj.setB(entry.getValue();
if(entry.getKey().equals("c")
obj.setC(entry.getValue();
}
}
Is there a better method to implement updateObj() apart of a complete if's chain?
Thank you all.