5

I have a Java method that takes a Method parameter:

void doSomethingWithMethod(Method m) {
    ...
}

And I have a Kotlin class that contains a function:

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. Is there an equivalent to the .java property that can be applied to a Kotlin class reference to get its Java equivalent?

If not, is there a workaround?

2 Answers 2

8
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. It can be added through Maven with the following dependency:

    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
        <version>${kotlin.version}</version>
    </dependency>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. The javaMethod property is part of the kotlin-reflect.jar which isn't the same as the standard library. While I was aware that there was a reflection library, seeing that javaClass was part of the standard library made me assume that javaMethod would be too.
0

You can use standard java reflection to get Method in kotlin:

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

or

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

Need no dependencies to do so.


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.