【问题标题】:@AutoAnnotation for Dagger 2 Multibinding Tutorial not working. How to get it working?Dagger 2 多绑定教程的 @AutoAnnotation 不起作用。如何让它工作?
【发布时间】:2019-10-06 09:48:57
【问题描述】:

提到https://dagger.dev/multibindings.html,有一段讲@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);
  }
}

不知何故,我从来没有让它工作。

我可以添加以下内容

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

还有添加

    android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

【问题讨论】:

    标签: java android annotations dagger-2


    【解决方案1】:

    要了解 AutoAnnotation 和 Dagger 2 的工作原理,首先我需要了解 AutoValue

    AutoValue sample: error: cannot find symbol class AutoValue_Animal

    然后跟着自动注解

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

    之后,我可以使用 AutoAnnotation 探索上面的 Dagger 2 示例。

    简而言之,AutoAnnotation 是一个 Java 代码生成器库,它生成可用于多绑定工作的值等价的 Annotation Key(因为 Java 类不像 Kotlin 数据类,因此需要这样的工具来使其值等价更容易)。

    Google 的 AutoValue 文档给出的示例并非开箱即用。需要进行一些修改,例如 1. 必须公开 MyComponentTest 以及函数。 2. AutoAnnotation 代码不应在 test 文件夹中,而应在实际源文件夹中。 3. 为了让 AutoAnnotation 与 Dagger 2 一起工作,我们需要以下设置

    android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
    

    我在https://github.com/elye/demo_android_dagger_autoannotation做了一个示例代码

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2020-09-18
    • 2014-01-29
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多