简体   繁体   English

通过与Kotlin的反射来调用类的构造函数

[英]Call class' constructor by reflection with Kotlin

I have the following data class 我有以下数据类

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

I need to call it's constructor by reflection. 我需要通过反射来调用它的构造函数。 I tried the following code 我尝试了以下代码

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

and call it with an array for the args parameter. 并使用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 : 使用entity: Class<T>cursor: Cursor来自本地数据库的cursor: Cursor Kotlin Documentation说:

When we call a vararg-function, we can pass arguments one-by-one, eg 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 *) 当我们调用vararg函数时,我们可以逐个传递参数,例如asList(1,2,3),或者,如果我们已经有一个数组并且想要将其内容传递给函数,我们使用传播operator(数组前缀为*)

but even with the * I keep getting the following exception : 但即使有*我仍然得到以下异常:

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. 调用newInstance()方法时必须使用spread运算符。 And the signature of createEntity() is wrong. createEntity()的签名是错误的。 I would recommend define it like that. 我建议像这样定义它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM