开发者

Replace own instance inside a java object

In my case the implementator shall be able to "update" an 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 haven't figured out how to replace all attributes at once. That approach doesn't work, but maybe there is some other chance to solve it:

    public void update(String newParams) {
//Can't replace "this" (that call returns an instance of "SameClass")
       this = ConnectionFramework.getF开发者_开发技巧orObject(SameClass.class,"some url",newParams); 
    }

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

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


You cannot replace 'this', you can replace the content (fields) of this, or replace the reference to this by another one...

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

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

method SameClassWrapper.update would be something like

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


You cannot set the "this" reference.

Since you cannot set the "this" reference, the best that you can do is fetch the object like so

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 of the "state" of the class it was to replace

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

an optimization is to set the fields directly.

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

however, with such an optimization, you must take care that shallow copying of the field is appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜