我一直在阅读有关中引入Android和我无法弄清楚它是如何工作的新体系结构组件:架构组件:ViewModelProvider如何知道要调用哪个构造函数?
ViewModelProviders.of(Activity).get(Class)
起初我以为它会调用默认的构造函数,并返回一个视图模型对象,你那么用例如实例化。一个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
但是指导那里,后来是这样的片段:
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);
}
里面的DefaultFactory
类的内部ViewModelProviders.java
。但是,这使我更加困惑。当ViewModel
对象没有将应用程序作为参数的构造函数时,getConstructor(Application.class)
如何工作?