简体   繁体   English

获取对Kotlin函数的引用作为Java方法

[英]Getting a reference to a Kotlin function as a Java Method

I have a Java method that takes a Method parameter: 我有一个带有Method参数的Java方法:

void doSomethingWithMethod(Method m) {
    ...
}

And I have a Kotlin class that contains a function: 我有一个包含函数的Kotlin类:

class MyClass {

    fun myFunction() : List<Something> {
        ...
    }

}

I can get a reference to the function with MyClass::myFunction , but I don't see a way to pass it into the doSomethingWithMethod method. 我可以使用MyClass::myFunction来获取对该函数的引用,但是我没有看到将它传递给doSomethingWithMethod方法的方法。 Is there an equivalent to the .java property that can be applied to a Kotlin class reference to get its Java equivalent? 是否有一个等效的.java属性可以应用于Kotlin类引用以获得其Java等价物?

If not, is there a workaround? 如果没有,是否有解决方法?

import kotlin.reflect.jvm.javaMethod

val method = MyClass::myFunction.javaMethod

The javaMethod property is not part of the standard Kotlin library, but is part of the official kotlin-reflect.jar . javaMethod属性不是标准Kotlin库的一部分,但是是官方kotlin-reflect.jar It can be added through Maven with the following dependency: 它可以通过Maven添加以下依赖项:

    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
        <version>${kotlin.version}</version>
    </dependency>

You can use standard java reflection to get Method in kotlin: 您可以使用标准的Java反射来获取Method在科特林:

MyClass::class.java.getMethod("myFunction")

or 要么

MyClass::class.java.getDeclaredMethod("myFunction")

Need no dependencies to do so. 不需要依赖。


Docs: 文档:
Method getMethod(String name, Class... parameterTypes) 方法getMethod(String name,Class ... parameterTypes)
Method getDeclaredMethod(String name, Class... parameterTypes) 方法getDeclaredMethod(String name,Class ... parameterTypes)

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

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