我有一个从持久性加载信息的函数,我只是以一种非常简单的方式告诉它它的类型。该类被称为,SharedPreferencesHelper.kt因此它是一个真正的生活问题解决者:
fun <T> loadList(context: Context, fileName: String, key: String, defValue: ArrayList<T>) : ArrayList<T> {
val gson = MyGsonDependency.getInstance()
val json = getWithFileName(context, fileName).getString(key, gson.toJson(defValue))
return gson.fromJson(json, object : TypeToken<ArrayList<T>>() {}.type)
}
Run Code Online (Sandbox Code Playgroud)
加载,例如,ArrayList<String>我只是这样做:
SharedPreferencesHelper.loadList<String>(
context,
FILE_NAME,
KEY,
ArrayList())
Run Code Online (Sandbox Code Playgroud)
我发现的问题是,当我运行Proguard并对代码进行混淆时,每当我调用时都会object : TypeToken<ArrayList<T>>() {}.type得到一个异常:
Caused by: java.lang.AssertionError: illegal type variable reference
at libcore.reflect.TypeVariableImpl.resolve(TypeVariableImpl.java:111)
at libcore.reflect.TypeVariableImpl.getGenericDeclaration(TypeVariableImpl.java:125)
at libcore.reflect.TypeVariableImpl.hashCode(TypeVariableImpl.java:47)
at java.util.Arrays.hashCode(Arrays.java:4074)
at com.google.gson.internal.$Gson$Types$ParameterizedTypeImpl.hashCode(Unknown Source:2)
at com.google.gson.reflect.TypeToken.<init>(Unknown Source:23)
Run Code Online (Sandbox Code Playgroud)
我找到的唯一解决方案是在这里,但这意味着要提供typeas参数。
我认为这是一个潜在的问题,原因有两个:
我的问题是,还有其他解决方法吗?