mardi 27 février 2018

How to modify the object value using the object name

How we can modify an Object Value when its path is available to us.

Consider below Person, Account and Department Class

// Person Class    
public class Person {
  private Integer id;
  private String name;
  private Integer age;
  private Account account;
  private List<Department> departments;
// setters and getters
}

// Account Class 
public class Account {
  private Integer id;
  private String accName;
  private String size;
// setters and getters
}

// Department Class
public class Department {
  private Integer deptId;
  private String deptName;
  private String deptSize;
// setters and getters
}

If there is a method which takes Person object as input and depending on the path i need to update the value of that same object then how it can be done?

public void method (Person person){
String path = "account.accName";
String newValue= "new value"

/*code to update the current value of accName with newValue*/
}

So here how will i update value of accName using path variable ? do i have to use reflection API ? if yes how ? or is there any other way to get it done. Kindly explain this at coding level as i am not able to get it .

Even for the list variable e.g i need to change deptName of second object in the list so for that

 String path = "departments[2].deptName";
 String newValue = "IT";

How this can be done?. Please provide your inputs.





Aucun commentaire:

Enregistrer un commentaire