Replace native instance inside java object

In my case, the developer should be able to "update" the object.

//creating an instance (follows the active record pattern) SameClass myObject = SameClass.find(123,params); //myObject gets replaced by the output of the web api inside, but it feels like an update for the implementator myObject.update("ask the web api to paint it black"); 

However, inside the class, I did not understand how to immediately replace all the attributes. This approach does not work, but perhaps there is another chance to solve it:

  public void update(String newParams) { //Can't replace "this" (that call returns an instance of "SameClass") this = ConnectionFramework.getForObject(SameClass.class,"some url",newParams); } 

The "ConnectionFramework" is actually a Spring RestTemplate for Android . Difficult version:

  public void update(HashMap<String,String> params) { SameClassResponse response = restTemplate.getForObject(ENDPOINT+"/{id}.json",SameClassResponse.class, params); this = response.getSameClass(); } 
+4
source share
2 answers

You cannot replace 'this', you can replace the contents (fields) of this or replace the link to it with another ...

One way to replace the 'this' link is to have a wrapper:

 SameClassWrapper myObject = new SameClassWrapper(SameClass.find(123,params)); myObject.update(params); 

the SameClassWrapper.update method will be something like

 { sameClass = code to build the new SameClass instance... } 
+4
source

You cannot set the "this" link.

Since you cannot set the "this" link, the best you can do is get the object this way

 public void update(String newParams) { //Can't replace "this" (that call returns an instance of "SameClass") SameClass fetchedObject = ConnectionFramework.getForObject(SameClass.class,"some url",newParams); 

and then set all the β€œstate” of the class that it was supposed to replace

  this.setValue1(fetchedObject.getValue1()); this.setvalue2(fetchedObject.getValue2()); ... 

The optimization is to set fields directly.

  this.field1 = fetchedObject.field1; this.field2 = fetchedObject.field2; ... 

however, with this optimization, you must ensure that inaccurate field copying is appropriate.

+2
source

Source: https://habr.com/ru/post/1339837/


All Articles