How can I use @AutoFactory with an @AutoValue class?

607 views Asked by At

Say I have a simple AutoValue class:

@AutoValue abstract class Foo {
  abstract CommonDependency commonDep();
  abstract String uniqueDataPerInstance();

  static Foo create(CommonDependency commonDep, String data) {
    return new AutoValue_Foo(commonDep, data);
  }
}

Now I want a factory so I don't need to pass commonDep each time I want a Foo. If this were not an AutoValue class, I could use AutoFactory for this trivially by annotating CommonDependency @Provided.

Do you know of a way to make these two code generators work well together?

1

There are 1 answers

0
tynn On BEST ANSWER

This is indeed a quite interesting problem, since the @AutoFactory annotation can only be applied to non-abstract classes.

error: Auto-factory doesn't support being applied to abstract classes.

For annotated constructors there was not even a useful error message after the compiler had failed.

Since there are only abstract or final auto-value classes in the code generation process, we'd have to annotate the last and final class. To do this you'd have to implement an auto-value extension, which mustBeFinal() and annotates the class declaration or the constructor of the final class with the @AutoFactory annotation.

Here's another issue taking effect, because the constructor parameters need to be annotated appropriately. So @Provided, @Nullable or any @Qualifier annotation need to be added there. The biggest issue here is, that @Provided defines @Target(PARAMETER) and with auto-value we only define methods.

If you don't want to implement it yourself, you could try to use auto-value-factory. I implemented it in the process to see, how both auto-libraries work together.