dimanche 16 août 2020

How To Obtain An Annotation Of A Function Literal At Runtime

package _z_additional

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.reflect.jvm.reflect

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
object _13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test {

    @Target(AnnotationTarget.FUNCTION)
    private annotation class A

    //@formatter:off
    @A private fun f1() {}
    private val f2: () -> Unit = @A {}
    private val f3: () -> Unit = @A fun() {}
    //@formatter:on

    @Test
    fun demonstrate_x() {
        listOf(::f1, f2.reflect(), f3.reflect()).filterNotNull().withIndex().forEach { (index, f) ->
            println("[$index] Function name = ${f.name}")
            println("[$index] Annotations = ${f.annotations.joinToString()}")
            println()
        }
    }

}

The output

[0] Function name = f1 [0] Annotations = @_z_additional._13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test$A()

[1] Function name = [1] Annotations =

[2] Function name = [2] Annotations =





Aucun commentaire:

Enregistrer un commentaire