Proguard is ruining my cleanliness. Gson and gener

2019-04-10 08:39发布

I have a function that loads information from persistence, and I just tell the type it is in a really simple way. The class is called SharedPreferencesHelper.kt so it is a really life problem solver:

    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)
    }

to load, for example, an ArrayList<String> I just do:

   SharedPreferencesHelper.loadList<String>(
            context,
            FILE_NAME,
            KEY,
            ArrayList())

The problem that I found is that when I run Proguard and obfuscate my code, whenever I call object : TypeToken<ArrayList<T>>() {}.type I get an exception:

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)

The only solution that I found was here but it would imply to provide the type as param.

I see this as a potential problem for two reasons:

  • It's not a warning, it's not a bad practice (is it?), and it's a really good function that saves much boilerplate code when loading a JSONArray that is Serialized afterwards. Developers of the same project might not be aware that this is a problem when Proguard is on the top.
  • The only way to test if a piece of code works is running Proguard, in other words, waiting for an average of 3 minutes for a build. Having a big test coverage in Unit and UI testing helps a lot too, but there are teams that don't have that possibility.

My question is, is there any other way to approach the problem?

0条回答
登录 后发表回答