老师,看了您的SharedPreferencesUtil封装的课程,做了一些优化,如下:class SharedPreferencesUtil<T>(context:Context, private val default:T ,spName:String = "default"):ReadWriteProperty<Any,T>{
private val sp by lazy { context.getSharedPreferences(spName,Context.MODE_PRIVATE)}
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return with(sp){
when(default){
is Int -> getInt(property.name,default)
else -> throw IllegalArgumentException("not support type")
}
} as T
}
@SuppressLint("CommitPrefEdits")
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
with(sp.edit()){
when(value){
is Int -> putInt(property.name,value)
else -> throw IllegalArgumentException("not support type")
}
}.apply()
}
}
去掉了name传参数,通过KProperty获取属性名称,我现在是想把default:T 传参也赋上值,比如判断T是Int就赋默认为0之类的,有没有什么方式能获取T的类型做个判断就不用传入default了,Int就默认是0,Boolean就默认false,String就默认""等等