【发布时间】:2017-06-18 19:32:53
【问题描述】:
我一直在阅读 Android 中引入的新架构组件,但我不知道它是如何工作的:
ViewModelProviders.of(Activity).get(Class)
最初我认为它会调用默认构造函数并返回一个 ViewModel 对象,然后您可以将其实例化,例如。根据
的 init() 方法public class UserProfileViewModel extends ViewModel {
private String userId;
private User user;
public void init(String userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
}
摘自指南:https://developer.android.com/topic/libraries/architecture/guide.html
但是,在指南的后面有这个 sn-p:
public class UserProfileViewModel extends ViewModel {
private LiveData<User> user;
private UserRepository userRepo;
@Inject // UserRepository parameter is provided by Dagger 2
public UserProfileViewModel(UserRepository userRepo) {
this.userRepo = userRepo;
}
public void init(String userId) {
if (this.user != null) {
// ViewModel is created per Fragment so
// we know the userId won't change
return;
}
user = userRepo.getUser(userId);
}
那么 ViewModelProvider 是如何知道调用提供的构造函数的呢?或者它看到只有 1 个构造函数并调用它?例如如果有 2 个构造函数会发生什么?
我尝试挖掘代码,发现:
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.getConstructor(Application.class).newInstance(mApplication);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
return super.create(modelClass);
}
在ViewModelProviders.java 内部的DefaultFactory 类内部。然而,这让我更加困惑。即使ViewModel 对象没有将应用程序作为参数的构造函数,getConstructor(Application.class) 如何工作?
【问题讨论】: