javabuilderauto-value

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.


Solution

  • 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.