gpt4 book ai didi

java - 使用 Kotlin 通过反射调用类的构造函数

转载 作者:IT老高 更新时间:2023-10-28 13:42:22 39 4
gpt4 key购买 nike

我有以下数据类

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 文档说:

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

谁能给我一些关于如何实例化我的类的提示?谢谢

最佳答案

在调用 newInstance() 方法时,您必须使用扩展运算符。 createEntity() 的签名是错误的。我建议这样定义。

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

关于java - 使用 Kotlin 通过反射调用类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36665039/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com