Runt
2025-03-14 cd771fa4b5d2762478099afdb445578de0fbe2df
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
            }
    }
}