samedi 26 octobre 2019

How to create a mutable list with a type retrieved via reflections

I am currently working on a deserialization problem which requires the population of a mutable list in kotlin with a generic type obtained via reflections. Specifically, I am provided with a function variable, and I need to make the mutable list's generic type equal to the return type of that function.

Returning a MutableList will not suffice -- I've tried something like below but that doesn't work. I've found a very similar problem on stackoverflow solved here, but I am having trouble converting it to kotlin: how to create a list of type obtained from reflection


val jsonArray = jsonTree.get("arrayFieldName") // returns jsonNode
val method: Method = retrieveMethod() // JsonNode::intValue / booleanValue / ...

val genericList = mutableListOf<method.returnType>()
for (item in jsonArray.elements())
  genericList.add(method.invoke(item))

return genericList




Aucun commentaire:

Enregistrer un commentaire