I have the following data class

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

我需要通过反射调用它的构造函数.我try 了以下代码

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)

With entity: Class<T> and cursor: Cursor from a local database 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 *)

但是,即使是*个,我仍然得到以下例外:

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

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

推荐答案

You have to use the spread operator when invoking the newInstance() method. And the signature of createEntity() is wrong. I would recommend define it like that.

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

Kotlin相关问答推荐

如果一项工作失败,请继续在Kotlin 等待其他工作/子元素完成

Kotlin:将泛型添加到列表任何>

有没有一种简单的方法来识别物体?

为什么可组合对象看似无状态(唯一传递的参数是函数,而不是状态),但会进行重组

为什么我的通用Kotlin函数中的这个转换未经判断?

将 java Optional 转换为 Kotlin Arrow Option

如何在 Spring Boot 3 中为内部类提供运行时提示

如何连接两个 kotlin 流?

比较 Kotlin 中的可比对象列表

如何禁用智能投射突出显示 Kotlin?

Kotlin 中的部分类委托

如何在 Kotlin 中判断数组类型(不是泛型类型)

将 @Component.Builder 与构造函数参数一起使用

无法为 retrofit2.Call 调用无参数构造函数

Jetpack Compose – LazyColumn 不重组

Jetpack Compose State:修改类属性

main函数和常规函数有什么区别?

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

是否在Kotlin中重写enum toString()?

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用