简体   繁体   English

如何在 Kotlin 中使用可变参数(参数数量)和反射

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

I've got this method (in java):我有这个方法(在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):我知道MyCustomObject的包名和类名以及方法名,所以我在反射期间使用它(使用 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.classContainingInsertMethod是较早创建的。 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.我尝试使用arrayOf(myCustomObjectClass)::class.java但这给了我另一个例外。 Using *myCustomObjectClass didn't work either.使用*myCustomObjectClass也不起作用。

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 (这里数组的大小和set调用的数量将对应于您要在 varargs 中传递的参数数量)然后

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

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

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