Are parameter methods on Kotlin functions visible in Java?


#1

I have a scenario where I want to pass a function defined in Kotlin to a Java class, which will then, in theory, analyze and process annotations on the method parameters. For example,

fun myFunc(@Anno1 a : Int, @Anno2 b: String) // …

If I then pass a reference to that function (::myFunc) to the Java method, I can’t see those annotations on the method parameters:

fun main(args: Array<String>) {
    ::myfunc2.javaClass.declaredMethods.forEach { m ->
        println("Method ${m.name}")
        val pa = m.parameterAnnotations
        pa.forEach { it ->
            val aa = it as Array<Annotation>
            aa.forEach { it ->
                val a = it as Annotation
                println("a = '$a'")
                println(a.javaClass.canonicalName)
            }
        }
    }
}

I get this output:
Method invoke
Method invoke
Method getName
Method getSignature
Method getOwner

I know I’m using Java reflection directly, which may differ in terms of functionality from the Kotlin reflection libraries, but I need to be able to see those annotations from Java code, which will, of course, not use the Kotlin reflection libs. Can somebody tell me what I’m doing wrong? Or maybe if what I’m trying to do is even possible?

Many thanks!

jason lee


#2

As far as I know they should be visible. Have you set the retention of the annotation to be runtime? https://kotlinlang.org/docs/reference/annotations.html#annotation-declaration


#3

The ones above are just examples. I’m actually using annotations defined by JAX-RS, which do have the appropriate retention policy.


#4

I managed to use the following Java code to print out the annotations. Please note AnnotationKt is derived from the kotlin file name (annotation.kt) where my “myFunc” lives. Please change it accordingly.

Annotation[][] a2 = AnnotationKt.class.getMethod("myFunc", int.class, String.class).getParameterAnnotations();
for (int i = 0; i < a2.length; i++) {
    for (int j = 0; j < a2[i].length; j++) {
        System.out.println(a2[i][j]);
    }
}