user2066880
user2066880

Reputation: 5024

Java: Setting "this" instance to an object of the same type

I have a POJO that has access to a method that returns an object of the same type (usually with some fields populated). Is it possible to implement a method in the POJO that calls this getter method and sets the instance of the POJO to reference the object that is returned? I would like to avoid setting a copy() function for every POJO that I create.

For example:

public class DAO {
    public static BaseEntity get(int id) {
        // returns some POJO
    }
}

public abstract class BaseEntity {
    public void get(int id) {
        BaseEntity entity = DAO.get(id);
        // sets "this" to the entity
    }
}

public class POJO extends BaseEntity {
    int foo;
    String bar; 
}

Upvotes: 0

Views: 57

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533660

If I could just call pojo.get(5) and the object is updated,

What you really want is just

 BaseEntity pojo = DAO.get(id);

The only way to change a reference to an object is to return it. Trying to wrapping it appears to just make your code more complicated in this case.

Upvotes: 1

Eran
Eran

Reputation: 393916

You can't assign to this.

You can have your get method return the new instance :

public BaseEntity get(int id) {
    return DAO.get(id);
}

And then assign that returned instance to the reference of the original instance:

BaseEntity pojo = new POJO ();
...
pojo = pojo.get(5);

Upvotes: 2

Related Questions