私は、Androidに導入し、私はこれがどのように動作するかを把握することはできません新しいアーキテクチャコンポーネントについて読んでてきた:アーキテクチャコンポーネント:ViewModelProviderはどのコンストラクタを呼び出すべきかをどのように知っていますか?
ViewModelProviders.of(Activity).get(Class)
当初、私はそれがデフォルトコンストラクタを呼び出して、あなたのViewModelオブジェクトを返すことを考えました例えばインスタンス化する。
public class UserProfileViewModel extends ViewModel {
private String userId;
private User user;
public void init(String userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
}
あたりなどのinit()メソッドのガイドから取られたスニペット: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つのコンストラクタが存在する場合、何が起こるでしょうか?
私は、コードを掘りしようと、何を私が見つけたことだった:ViewModelProviders.java
内部DefaultFactory
クラスの内部
@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);
}
。しかし、これはさらに私を混乱させました。 ViewModel
オブジェクトに、アプリケーションを引数として持つコンストラクタがない場合、getConstructor(Application.class)
はどのように動作しますか?