Dagger 2 - 如何注入一个我无法控制其对象实例化的类

Ahm*_*azy 6 android dependency-injection dagger-2

我有一个通过插入“.class”链接到另一个库的类,所以我不知道如何在这个类中注入依赖项,因为我不是创建对象的人,而库只是实例化具有默认构造函数的类。

例子:

这是 Room 的转换器类

public class AttendeeListConverter {

    @TypeConverter
    public List<Attendee> fromJson(String attendeesJson) {
        if (attendeesJson == null) {
            return null;
        }
        return gson.fromJson(attendeesJson, new TypeToken<List<Attendee>>() { }.getType());
    }
}
Run Code Online (Sandbox Code Playgroud)

我想注入我的 Gson 单例实例,但我不是创建该转换器类的对象的人,我只是传递“AttendeesListConverter.class”,并且对象本身的创建是代码生成的。

Dav*_*jak 2

如果您既不控制对象创建,也不在之后访问对象实例,我认为没有一个干净的解决方案。

在这种情况下,您唯一能做的就是从对象中获取一个组件并让它自行注入。

class Injector {
  public static AppComponent component;
}

class AttendeeListConverter {

  public AttendeeListConverter() {
    AppComponent component = Injector.component
    component.inject(this);
  }
}

// and initialize it in onCreate of your Application

class MyApp extends Application {
  @Inject AppComponent appComponent;

  onCreate() {
    // ...setup...

    Injector.component = appComponent
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,您也可以将组件静态存储在应用程序本身中,或者有些人也喜欢将应用程序存储在静态变量中,以便您可以使用MyApp.appComponent.inject()