Dagger 将接口注入私有字段

Dagger inject interface into private fields

我想在抽象 class 构造函数中注入接口实现并在子 class 中使用它。

我有编译时错误:

Error:Gradle: Dagger does not support injection into private fields
Error:Gradle: Example.A cannot be provided without an @Provides-annotated method.
Error:Gradle: Example.B cannot be provided without an @Inject constructor or from an @Provides-annotated method.
Error:Gradle: Execution failed for task ':app:compileDemoDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

kotlin 中的示例。

   object Example {
    interface IData {

        fun foo() {
        }
    }

    class Data : IData {

    }

    @Module
    class DataModel {
        @Provides
        fun data(): IData = Data()
    }

    @Singleton
    @Component(modules =
    arrayOf(DataModel::class)
    )
    interface Injector {
        fun inject(a: A)
        fun inject(b: B)
    }

    val graph: Injector = DaggerInjector.builder().
            dataModel(DataModel()).
            build()

    abstract class A {

        @Inject var data: IData ? = null

        public open fun setUp() {
            graph.inject(this)
        }
    }

    open class B : A() {

        override fun setUp() {
            super.setUp()
            data!!.foo()
        }
    }

    fun bar() {
        val a = B()
        a.setUp()
    }
}

版本:


这是案例。反编译java

  public static class A {
  @Inject
  @Nullable
  private Example.IData data;

  @Nullable
  protected final Example.IData getData() {
     return this.data;
  }

  protected final void setData(@Nullable Example.IData <set-?>) {
     this.data = <set-?>;
  }

  public void setUp() {
     Example.INSTANCE.getGraph().inject(this);
  }

}

从错误消息来看,我认为问题出在这一行:

@Inject var data: IData ? = null

此 属性 的支持字段是 private,这就是错误的内容。通常 lateinit 关键字用于这种情况:

@Inject lateinit var data: IData

lateinit 是直接使用 属性 的访问级别(此处为 public)公开支持字段的几个修饰符之一,使其对 Dagger 生成的 类.