samedi 16 avril 2016

Call class' constructor by reflection with Kotlin

I have the following data class

data class Person (val id: Int? = null, val name: String, val active: Boolean)

I need to call it's constructor by reflection. I tried the following code

private fun <T> createEntity(constructor: Constructor<*>, vararg args: T) : Any {
    return constructor.newInstance(args)
}

and call it with an array for the args parameter. Kotlin Documentation says :

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *)

but even with the * I keep getting the following exception :

java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 1

Can anyone give me some tips on how to instantiate my class? Thanks





Aucun commentaire:

Enregistrer un commentaire