Search code examples
javaaws-lambdadagger-2copy-constructor

Is there a shorthand to copy an object within a constructor?


Is there some way to achieve this = that in a constructor? that is an object that I want to copy (and thus is an object of the same class as this, this being the object reference).

class Foo {

  private final Bar bar;

  public Foo() {
    Foo that = DaggerFactory.create().getFoo();
    // this = that; but it's not working!?
  }
  
  @Inject
  public Foo(Bar bar) {
    this.bar = bar;
  }

  // Other methods
}

I've seen examples of copy constructors where they copied the members one by one i.e. this.bar = that.bar. This is my last option as I've got a handful of members in the class, and I don't want to unnecessarily "clutter" my code.

P.S. I do want to instantiate the objects through the empty constructor as that's how AWS Lambda works (where I will be deploying this). So far I haven't found any way where I could get Lambda to use Dagger provided objects. If there is a better approach with respect to Lambda / Dagger that would also be great!


Solution

  • There is no clever (shortcut / shorthand) way to write a copy constructor in Java. At the source code level you must assign the fields one at a time.

    Normally, I would just "bite the bullet" and write the code. But there are a couple of other alternatives:

    • Your IDE may have a way to generate a copy constructor. (Eclipse doesn't, but apparently you can generate a regular constructor for all field, and then do some clever search-replace stuff on the generated code; see Eclipse generate copy constructor)

    • You could conceivably write some reusable code that copies fields from one object to another using reflection. This is rather inefficient, but it might be acceptable if you have to deal with classes that have a ridiculous number of fields.

    • You could use the clone() mechanism instead.