Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
How to copy/transform an AutoValue object with builder

I'm playing auto-value with builder recently. And I'm in such a situation, say I have to transform an existing object to a new one with a few properties get updated. The example code is here:

@AutoValue
public abstract class SomeObject {
    public static Builder builder() {
      ...
    }

    public abstract String prop1();
    public abstract int prop2();

    // Populate a builder using the current instance.        
    public Builder newBuilder() {
        ...
    }
}

Notice I wrote a newBuilder method, so that I can do the transformation like this:

SomeObject resultedObject = originObject.newBuilder()
    .setProp2(99)
    .build();

Yes, I can write the newBuilder like this:

public Builder newBuilder() {
    return new AutoValue_SomeObject.Builder()
            .setProp1(this.prop1())
            .setProp2(this.prop2());
}

But there should be a better way, especially when dealing with complex objects in real life. Something like this is way better:

public Builder newBuilder() {
    return new AutoValue_SomeObject.Builder(this);
}

Unfortunately, the generated constructor Builder(SomeObject) is private, and I cannot find any reference to it.

So what's your thoughts about the problem?

The AutoValue version is 1.4-rc2. Thanks in advance.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Please refer to JakeWharton's reply

The answer is to declare a toBuilder method in SomeObject

public abstract Builder toBuilder();

the generated sub-class will implement this method.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!