samedi 27 novembre 2021

Kotlin Android reflection get class in runtime

I have a response from the server that returns me different objects and each object has a type. How I can match class in runtime with the type I get from the response? This code for example works but I am trying to get rid of the when statement and make it more dynamic.

   JsonParser.parseString(jsonArrayString).asJsonArray
            .map { tileJsonObject ->
                tileJsonObject as JsonObject
                val tile = when (tileJsonObject.get("type").asString) {
                    Red.TYPE -> Red::class.java
                    Blue.TYPE -> Blue::class.java
                    else -> Red::class.java
                }
                Gson().fromJson(tileJsonObject, tile)
            }
    }




Aucun commentaire:

Enregistrer un commentaire