简体   繁体   中英

How to work with varargs (number of arguments) and reflection in Kotlin

I've got this method (in java):

public void insert(final MyCustomObject... obj)

I know the package name and the class name of MyCustomObject as well as the method name so I am using it during reflection (using Kotlin):

val myCustomObjectClass = Class.forName("${packageName}${className}")
val myCustomObject = myCustomObjectClass.getConstructor(String::class.java, Long::class.java)
val insertMethod = classContainingInsertMethod.getDeclaredMethod("insert", myCustomObjectClass)

the class classContainingInsertMethod was created earlier. Now, how could I invoke the method? I got an exception that there is no such method. I am aware of that because it is a number of args, not a single one.

I tried using arrayOf(myCustomObjectClass)::class.java but this gave me just another exception. Using *myCustomObjectClass didn't work either.

import java.lang.reflect.Array
val varArg = Array.newInstance(myCustomObjectClass, 1)
val varArgClass = varArg::class.java
val myCustomObjectConstructor = myCustomObjectClass.getConstructor(String::class.java, Long::class.java)
val myCustomObjectElement = myCustomObjectConstructor.newInstance("", 0L)
Array.set(varArg, myCustomObjectElement, 0)

(here the size of array and number of set calls will correspond to the number arguments you want to pass in varargs) and then

val insertMethod = classContainingInsertMethod.getDeclaredMethod("insert", varArgClass)
insertMethod.invoke(instanceOfClassContainingInsertMethod, varArg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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