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.getForObject(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();
}
We use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor of the class to create the object.
clone() method. Java clone() method creates a copy of an existing object. It is defined in Object class. It returns clone of this instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With