package com.runt.open.mvi.base.model
|
|
import android.util.Log
|
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModelProvider
|
import java.lang.reflect.InvocationTargetException
|
|
/**
|
* @author Runt(qingingrunt2010 @ qq.com)
|
* @purpose
|
* @date 6/1/24
|
*/
|
class ViewModelFactory : ViewModelProvider.Factory {
|
|
|
override fun <T : ViewModel> create(modelClass : Class<T>) : T {
|
return try {
|
modelClass.getDeclaredConstructor().newInstance()
|
} catch (e : InstantiationException) {
|
throw RuntimeException("(创建实例失败,没有对应的构造方法,请重写一个实现类)Cannot create an instance of $modelClass" , e)
|
} catch (e : IllegalAccessException) {
|
throw RuntimeException("Cannot create an instance of $modelClass" , e)
|
}catch (e : UnsatisfiedLinkError) {
|
throw RuntimeException("Cannot create an instance of $modelClass" , e)
|
}catch (e : InvocationTargetException){
|
Log.e("ViewModelFactory" , "create: ${e.cause}" , );
|
e.cause?.printStackTrace()
|
throw RuntimeException("Cannot create an instance of $modelClass" , e)
|
}
|
}
|
|
companion object {
|
var sInstance : ViewModelFactory? = null
|
val instance : ViewModelFactory?
|
get() {
|
if (sInstance == null) {
|
sInstance = ViewModelFactory()
|
}
|
return sInstance
|
}
|
}
|
}
|