gpt4 book ai didi

java - 带有 Kotlin 的 Dagger 2,在 ApplicationComponent 中返回具有泛型的类型

转载 作者:IT老高 更新时间:2023-10-28 13:47:24 25 4
gpt4 key购买 nike

我想返回泛型类型以由子图公开,问题出在自动生成的 java 类中,我尝试做一些事情,但解决它的一种方法是从 AppComponent 中删除泛型类型和返回简单对象。还有更“正确”的方法吗?

这是 AppComponent

@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(activity: BaseActivity<MvpView, MvpPresenter<MvpView>>)

//...
fun dataBase(): Database<Realm>
}

这是 ApplicationModule 中的函数

@Provides @Singleton fun provideDatabase(@AppContext context: App): Database<Realm> {
Realm.init(context)
val config = RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.name("db")
.build()
Realm.setDefaultConfiguration(config)
return RealmDatabase(Realm.getDefaultInstance())
}

那么我想收到我的数据库

@Provides @ActivityScope fun provideDich(database: Database<Realm>) = Someobject(database)

然后我看到日志显示:

**Error:com.test.data.storage.Database<? extends io.realm.Realm> cannot be provided without an @Provides-annotated method.**

因为 dagger2 生成这样的工厂并且有 java 掩码

    public final class Logout_Factory implements Factory<Logout> {
private final MembersInjector<Logout> logoutMembersInjector;

private final Provider<SessionStorage.CloudStorage> arg0Provider;

private final Provider<Database<? extends Realm>> arg1Provider;

public Logout_Factory(
MembersInjector<Logout> logoutMembersInjector,
Provider<SessionStorage.CloudStorage> arg0Provider,
Provider<Database<? extends Realm>> arg1Provider) {
assert logoutMembersInjector != null;
this.logoutMembersInjector = logoutMembersInjector;
assert arg0Provider != null;
this.arg0Provider = arg0Provider;
assert arg1Provider != null;
this.arg1Provider = arg1Provider;
}

@Override
public Logout get() {
return MembersInjectors.injectMembers(
logoutMembersInjector, new Logout(arg0Provider.get(), arg1Provider.get()));
}

public static Factory<Logout> create(
MembersInjector<Logout> logoutMembersInjector,
Provider<SessionStorage.CloudStorage> arg0Provider,
Provider<Database<? extends Realm>> arg1Provider) {
return new Logout_Factory(logoutMembersInjector, arg0Provider, arg1Provider);
}
}

最佳答案

我遇到了同样的问题,我找到了解决方案。

您需要在您的 @Provide 方法返回类型中声明 @JvmWildcard

@Provides 
@Singleton
fun provideDatabase(@AppContext context: App): Database<@JvmWildcard Realm> {
Realm.init(context)
val config = RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.name("db")
.build()
Realm.setDefaultConfiguration(config)
return RealmDatabase(Realm.getDefaultInstance())
}

关于java - 带有 Kotlin 的 Dagger 2,在 ApplicationComponent 中返回具有泛型的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41566518/

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