javagenericscode-generationauto-value

How to skip generation of testBuilder with AutoValue in generic class


Autovalue version: 1.3

Given the following class:

@AutoValue
public abstract class SimpleClass<T> {
    public static <E> SimpleClass<E> create(Set<? extends E> someField) {
        return SimpleClass.<E>builder().someField(someField).build();
    }

    public static <E> Builder<E> builder() {
        return new AutoValue_SimpleClass.Builder<E>();
    }

    public abstract ImmutableSet<T> someField();

    @AutoValue.Builder
    public abstract static class Builder<T> {
        public abstract Builder<T> someField(Set<? extends T> someField);
        public abstract SimpleClass<T> build();
    }
}

When auto builder generates the sources for the above class, it generates something like:

final class AutoValue_SimpleClass<T> extends $AutoValue_SimpleClass<T> {
  AutoValue_SimpleClass(ImmutableSet<T> someField) {
    super(someField);
  }

  static SimpleClass.Builder<E> testBuilder() {
      return builder();
  }
}

Notice how the generic method testBuilder is incorrectly generated because it needs <E> after static.

This is what should have been generated:

static <E> SimpleClass.Builder<E> testBuilder() {
    return builder();
}

Is there a way to not have this testBuilder method generated or a way to ensure that AutoValue generates the right sources?

Thanks.

EDIT: Just updated to 1.4 and the same thing is still happening

Issue on GH: https://github.com/google/auto/issues/511


Solution

  • Solution was surprisingly not too involved:

    Just rename the static builder method

    @AutoValue
    public abstract class SimpleClass<T> {
        public static <E> SimpleClass<E> create(Set<? extends E> someField) {
            return SimpleClass.<E>getBuilder().someField(someField).build();
        }
    
        public static <E> Builder<E> getBuilder() {
            return new AutoValue_SimpleClass.Builder<E>();
        }
    
        public abstract ImmutableSet<T> someField();
    
        @AutoValue.Builder
        public abstract static class Builder<T> {
            public abstract Builder<T> someField(Set<? extends T> someField);
            public abstract SimpleClass<T> build();
        }
    }
    

    This means testBuilder method is no longer generated.