【发布时间】:2016-04-16 13:52:46
【问题描述】:
我有以下数据类
data class Person (val id: Int? = null, val name: String, val active: Boolean)
我需要通过反射调用它的构造函数。我尝试了以下代码
private fun <T> createEntity(constructor: Constructor<*>, vararg args: T) : Any {
return constructor.newInstance(args)
}
并使用args 参数的数组调用它。
val fields = entity.declaredFields
var elements = Array<Any>(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)
使用来自本地数据库的 entity: Class<T> 和 cursor: Cursor
Kotlin 文档说:
当我们调用一个可变参数函数时,我们可以一个接一个地传递参数,例如asList(1, 2, 3),或者,如果我们已经有一个数组并且想要将其内容传递给函数,我们使用扩展运算符(以 * 为数组前缀)
但即使使用*,我仍然收到以下异常:
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 1
谁能给我一些关于如何实例化我的类的提示?谢谢
【问题讨论】:
-
你必须在这里使用扩展运算符。你如何调用
createEntity? -
我编辑了我的问题@Michael,如您所见,我使用了扩展运算符
标签: java android reflection kotlin