mercredi 22 janvier 2020

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.





Aucun commentaire:

Enregistrer un commentaire