我有以下数据类
data class Person (val id: Int? = null, val name: String, val active: Boolean)
我需要通过反射来调用它的构造函数.我尝试了以下代码
private fun createEntity(constructor: Constructor, vararg args: T) : Any {
return constructor.newInstance(args)
}
并使用args参数的数组调用它.
val fields = entity.declaredFields
var elements = Array(getFieldsCount(fields), { i ->
val index = cursor.getColumnIndex(fields[i].name.toUpperCase())
when (fields[i].type) {
kotlin.Int::class.java -> cursor.getInt(index)
kotlin.Boolean::class.java -> if (cursor.getInt(index) == 1) true else false
else -> cursor.getString(index)
}
})
val test = createEntity(entity.constructors.first(), *elements)
使用实体:Class< T>和cursor:来自本地数据库的游标
Kotlin文档说:
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 *)
但即使有*我仍然得到以下异常:
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 1
谁能给我一些关于如何实例化我的课程的技巧?谢谢