Call class' constructor by reflection with Kotlin
<p>I have the following data class</p>

<pre><code>data class Person (val id: Int? = null, val name: String, val active: Boolean)
</code></pre>

<p>I need to call it's constructor by reflection. I tried the following code </p>

<pre><code>private fun &lt;T&gt; createEntity(constructor: Constructor&lt;*&gt;, vararg args: T) : Any {
    return constructor.newInstance(args)
}
</code></pre>

<p>and call it with an array for the <code>args</code> parameter. </p>

<pre><code>val fields = entity.declaredFields
var elements = Array&lt;Any&gt;(getFieldsCount(fields), { i -&gt;
    val index = cursor.getColumnIndex(fields[i].name.toUpperCase())
    when (fields[i].type) {
        kotlin.Int::class.java -&gt; cursor.getInt(index)
        kotlin.Boolean::class.java -&gt; if (cursor.getInt(index) == 1) true else false
        else -&gt; cursor.getString(index)
    }

})
val test = createEntity(entity.constructors.first(), *elements)
</code></pre>

<p>With <code>entity: Class&lt;T&gt;</code> and <code>cursor: Cursor</code> from a local database
Kotlin Documentation says :</p>

<blockquote>
  <p>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 *)</p>
</blockquote>

<p>but even with the <code>*</code> I keep getting the following exception : </p>

<pre><code>java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 1
</code></pre>

<p>Can anyone give me some tips on how to instantiate my class? Thanks</p>