在指代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
要了解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代码生成器库,它生成等效于值的注释键,该键可用于多重绑定工作(因为Java类与Kotlin Data Class不同,因此需要这样的工具才能使它等效于值) )。
Google的AutoValue文档给出的示例不是开箱即用的。需要进行一些修改,例如1.必须公开MyComponentTest和函数。2. AutoAnnotation代码不应位于测试文件夹中,而应位于实际的源文件夹中。3.为了使自动注释与Dagger 2配合使用,我们需要以下设置
android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
我在https://github.com/elye/demo_android_dagger_autoannotation中创建了示例代码