Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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();
}
like image 745
OneWorld Avatar asked Feb 15 '11 15:02

OneWorld


People also ask

What method can be used to create a new instance of an object?

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.

How to create new object from existing object in Java?

clone() method. Java clone() method creates a copy of an existing object. It is defined in Object class. It returns clone of this instance.


2 Answers

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...
}
like image 155
pgras Avatar answered Oct 02 '22 14:10

pgras


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.

like image 34
Edwin Buck Avatar answered Oct 02 '22 14:10

Edwin Buck