如何在 Hilt 限定符的 AnnotationRetention.BINARY 和 AnnotationRetention.RUNTIME 之间做出选择?

问题描述 投票:0回答:1

我如何知道对于 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
android kotlin dependency-injection annotations dagger-hilt
1个回答
0
投票

我不使用 Hilt,但看起来它只是 Dagger2 的 Android 扩展。

所以,让我们从

AnnotationRetention
枚举中的选项开始,它们从最弱到最强

  • SOURCE
    注释不会保留在编译后的代码中,它在编译时几乎存在,但随后被剥离
  • BINARY
    将在编译后的代码中可用,但通过反射不可见
  • RUNTIME
    将保留在编译后的代码中,并且可以通过反射读取

Dagger2 不使用反射来解决依赖关系。相反,它在构建时通过

kapt
构建依赖关系图。

AndroidDevelopers.com 上的 Hilt 文档中,他们使用

AnnotationRetention.BINARY
政策。

尽管考虑到我上面写的内容,使用

AnnotationRetention.SOURCE
应该是完全可以的,因为在图形生成过程中存在注释才重要。它对我来说非常有效。

© www.soinside.com 2019 - 2024. All rights reserved.