我如何知道对于 Hilt 限定符使用
AnnotationRetention.BINARY
还是 AnnotationRetention.RUNTIME
?例如。从Medium Article看这段代码,它似乎是混合的(不确定作者是否有意这样做):
// CoroutinesQualifiers.kt file
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MainDispatcher
@Retention(AnnotationRetention.BINARY) <================== once binary
@Qualifier
annotation class MainImmediateDispatcher
我不使用 Hilt,但看起来它只是 Dagger2 的 Android 扩展。
所以,让我们从
AnnotationRetention
枚举中的选项开始,它们从最弱到最强
SOURCE
注释不会保留在编译后的代码中,它在编译时几乎存在,但随后被剥离BINARY
将在编译后的代码中可用,但通过反射不可见RUNTIME
将保留在编译后的代码中,并且可以通过反射读取Dagger2 不使用反射来解决依赖关系。相反,它在构建时通过
kapt
构建依赖关系图。
在 AndroidDevelopers.com 上的 Hilt 文档中,他们使用
AnnotationRetention.BINARY
政策。
尽管考虑到我上面写的内容,使用
AnnotationRetention.SOURCE
应该是完全可以的,因为在图形生成过程中存在注释才重要。它对我来说非常有效。