gpt4 book ai didi

android - Dagger 2 - 如何注入(inject)一个我不控制其对象实例化的类

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:39 24 4
gpt4 key购买 nike

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

例子:

这是 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());
}
}

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

最佳答案

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

鉴于这些情况,您唯一可以做的就是从对象中获取一个组件并让它注入(inject)自身。

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
}
}

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

关于android - Dagger 2 - 如何注入(inject)一个我不控制其对象实例化的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com