lundi 30 décembre 2019

Kotlin read property annotation via reflection

I've created an annotation for properties and now I want to read it via reflection at runtime. In my opinion I'm doing everything right but there's no annotation.

Why isn't the annotation not available?

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
annotation class MyAnnotation

class MyClass(@MyAnnotation val attr: List<String>)

fun main(args: Array<String>) {
    var prop = MyClass::attr
    prop.annotations.forEach { println("prop.annotations -> " + it) }
    prop.javaClass.getAnnotations().forEach { println("prop.javaClass.getAnnotations -> " + it) }
    println("isAnnotationPresent -> ${prop.javaClass.isAnnotationPresent(MyAnnotation::class.java)}")
}

Output:
prop.javaClass.getAnnotations -> @kotlin.Metadata(xi=0, bv=[1, 0, 3], mv=[1, 1, 16], k=3, xs=, d1=[], d2=[], pn=) isAnnotationPresent -> false





Aucun commentaire:

Enregistrer un commentaire