Getting a reference to a Kotlin function as a Java method

I have a Java method that takes a parameter Method:

void doSomethingWithMethod(Method m) {
    ...
}

And I have a Kotlin class that contains a function:

class MyClass {

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

}

I can get a link to a function using MyClass::myFunction, but I see no way to pass it to a method doSomethingWithMethod. Is there an equivalent property .javathat can be applied to a Kotlin class reference to get the Java equivalent?

If not, is there a workaround?

+4
source share
2 answers
import kotlin.reflect.jvm.javaMethod

val method = MyClass::myFunction.javaMethod

The property is javaMethodnot part of the Kotlin standard library, but is part of the official one kotlin-reflect.jar. It can be added via Maven with the following dependency:

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

java Method kotlin:

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

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

.


:
getMethod (String name, Class... parameterTypes)
getDeclaredMethod (String name, Class... parameterTypes)

0

All Articles