0

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; 
}
3
  • What has that got to do with a 'set this' ? Since you can't instantiate BaseEntity, there will be no 'this' anyway. Commented Jan 20, 2015 at 7:48
  • POJO extends BaseEntity, so I'd like to be able to do something like pojo.get(123) to populate its fields. Commented Jan 20, 2015 at 7:49
  • I understand what you are trying to do. I just don't get the logic of your 'how'. I would recommend an interface (not an abstract class) and a (concrete) implementation of that interface. Commented Jan 20, 2015 at 7:51

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I see, this makes sense. Something that seems weird to me is that pojo = pojo.get(5) seems a bit redundant. If I could just call pojo.get(5) and the object is updated, then that seems a lot more natural. Is my thought process correct?
The first new POJO(); is likely to be redundant.
@PeterLawrey The idea was to call an instance method that changes that instance (since that's what the OP seems to want), so an initial instance must be created in order to call pojo.get(5). Of course, you can directly call the static method.
@user2066880 For that purpose, pojo.get(5) would have to change the state of the existing instance. It can't change the pojo variable to refer to a different instance.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.