Search code examples
javaandroidannotationsdagger-2

@AutoAnnotation for Dagger 2 Multibinding Tutorial not working. How to get it working?


In referring to https://dagger.dev/multibindings.html, there's a section talking about @AutoAnnotation

class MyComponentTest {
  @Test void testMyComponent() {
    MyComponent myComponent = DaggerMyComponent.create();
    assertThat(myComponent.myKeyStringMap()
        .get(createMyKey("abc", Abc.class, new int[] {1, 5, 10}))
        .isEqualTo("foo");
  }

  @AutoAnnotation
  static MyKey createMyKey(String name, Class<?> implementingClass, int[] thresholds) {
    return new AutoAnnotation_MyComponentTest_createMyKey(name, implementingClass, thresholds);
  }
}

Somehow I never get it working.

I get to add to gradle the following

    implementation 'com.google.auto.value:auto-value:1.5.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.5.2'

And also add

    android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

Solution

  • To get to understand how AutoAnnotation and Dagger 2 works, first I need to understand AutoValue

    AutoValue sample: error: cannot find symbol class AutoValue_Animal

    Then follow by AutoAnnotation

    What is @AutoAnnotation for? How could it be used?

    After that, then I could explore the Dagger 2 example above with AutoAnnotation.

    In short, AutoAnnotation is a Java code generator library that generate value-equivalent Annotation Key that could be used for multi-binding works (since Java classes are not like Kotlin Data Class, hence need such tool to make it value-equivalent easier).

    The example given by Google's AutoValue document is not working out of the box. Several modification needed e.g. 1. Have to make the MyComponentTest public, as well as the function. 2. The AutoAnnotation code shouldn't be in the test folder, but in the actual source folder. 3. In order for AutoAnnotation to work with Dagger 2, we'll need the below setting

    android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
    

    I have made an example code in https://github.com/elye/demo_android_dagger_autoannotation