简体   繁体   中英

Replacing ImmutableMap keys in AutoValue with toBuilder()

I've come across a problem when using AutoValue with geneated Builder and fields with Guava ImmutableMap.

Say we have this Container value class:

public abstract class Container {
   
   public abstract ImmutableMap<String, String> metadata();

   public abstract Builder toBuilder();

   public static Builder builder() {
      return new AutoValue_Container.Builder();
   }

   @AutoValue.Builder
   public abstract static class Builder {

      public abstract ImmutableMap.Builder<String, String> metadataBuilder();
   
      public final Builder addMetadata(String key, String value)  {
         metadataBuilder().put(key, value);
         return this;
      }
   }
}

When I want to do the following, the ImmutableMap builder throws java.lang.IllegalArgumentException: Multiple entries with same key

aContainer.toBuilder().addMetadata("existingKey", "someNewValue");

Does anyone familiar with AutoValue know how to coax the implementation to do as told?

There's a documented workaround in the builders-howto documentation . Quote:

  @AutoValue
  public abstract class Foo {
    public abstract ImmutableMap<Integer, String> map();
    ...

    @AutoValue.Builder
    public abstract static class Builder {

      private final ImmutableMap.Builder<Integer, String> mapBuilder = ImmutableMap.builder();

      public ImmutableMap.Builder<Integer, String> mapBuilder() {
        return mapBuilder;
      }

      abstract Builder setMap(ImmutableMap<Integer, String> map); // not public

      abstract Foo autoBuild(); // not public

      public Foo build() {
        setMap(mapBuilder.buildKeepingLast());
        return autoBuild();
      }

      ...

      // #start
      // Needed only if your class has toBuilder() method
      public Builder toBuilder() {
        Builder builder = autoToBuilder();
        builder.mapBuilder().putAll(map());
        return builder;
      }

      abstract Builder autoToBuilder(); // not public
      // #end
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM