我正在尝试实例化我的视图模型,但出现此错误
原因:java.lang.NoSuchMethodException: [class com.test.domain.PostUserTokenImpl] at java.lang.Class.getConstructor0(Class.java:2327( at java.lang.Class.getConstructor(Class.java:1725( at com.test.presentation.viewmodel.LoginVMFactory.create(LoginVMFactory.kt:13(
我尝试做一个保存和接口的视图模型实例
视图
private val viewModel by lazy { ViewModelProviders.of(this, LoginVMFactory(PostUserTokenImpl(UserRepoImpl()))).get(LoginViewModel::class.java) }
LoginVMFactory
class LoginVMFactory(private val useCase: PostUserTokenImpl):ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(PostUserTokenImpl::class.java).newInstance(useCase)
}
}
登录视图模型
class LoginViewModel(private val useCase: PostUserToken): ViewModel() {
...
}
后用户令牌
interface PostUserToken {
suspend fun postUserToken(user: User): Resource<Boolean>
}
PostUserTokenImpl
class PostUserTokenImpl(private val repo: UserRepo): PostUserToken {
override suspend fun postUserToken(user:User):Resource<Boolean> = repo.saveUserToken(user)
}
知道为什么会这样吗?我怀疑这可能是因为我们无法使用接口实例化我们的视图模型?
将我的实现更改为
class LoginVMFactory(private val useCase: PostUserToken):ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(PostUserToken::class.java).newInstance(useCase)
}
}
然后在我看来
private val viewModel by lazy { ViewModelProviders.of(this, LoginVMFactory(PostUserTokenImpl(UserRepoImpl()))).get(LoginViewModel::class.java) }