Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
xinthink Avatar asked Mar 14 '17 08:03

xinthink


People also ask

How to generate AutoValue Java?

In order to generate a value-type object all you have to do is to annotate an abstract class with the @AutoValue annotation and compile your class. What is generated is a value object with accessor methods, parameterized constructor, properly overridden toString(), equals(Object) and hashCode() methods.

How to use AutoValue?

How to use AutoValue. The AutoValue concept is extremely simple: You write an abstract class, and AutoValue implements it. That is all there is to it; there is literally no configuration. Note: Below, we will illustrate an AutoValue class without a generated builder class.

How do I make an AutoValue?

To add AutoValue to your project, you simply need to add its single dependency to your annotation processing classpath. This ensures that no dependencies of AutoValue get added to your final artifact, only the generated code.


1 Answers

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.

like image 66
xinthink Avatar answered Sep 22 '22 14:09

xinthink