Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

reflection - Jackson annotation not visible via Kotlin Reflect

For some reason Kotlin Reflect does see my custom annotation on member property but doesn't see Jackson one. Though Jackson annotation is detected and used by Jackson itself. Minimum snippet (run in REPL thus Line_5$A classname):

annotation class A
 
 class C {
     @A
     @com.fasterxml.jackson.annotation.JsonProperty
     var x: Int = 0
 }
 
 C::class.memberProperties.forEach { println(it.annotations.map{it.annotationClass}) }

Output: [class Line_5$A]

Expected: [class Line_5$A, class com.fasterxml.jackson.annotation.JsonProperty]

How could I have access to Jackson annotation here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, found out that Jackson annotation was attached to Java field, not Kotlin property. So this workaround works:

println(C::class.memberProperties.first().javaField!!.declaredAnnotations.get(0).annotationClass)

Output: class com.fasterxml.jackson.annotation.JsonProperty

UPD: And if data class is used then this:

import kotlin.reflect.full.primaryConstructor
 
 data class C (
     @com.fasterxml.jackson.annotation.JsonProperty
     var x: Int = 0
 )
 
 val prop = C::x
 println(C::class.primaryConstructor
     ?.parameters
     ?.find { it.name == prop.name }
     ?.annotations
     ?.first()
     ?.annotationClass
 )

Output: class com.fasterxml.jackson.annotation.JsonProperty


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...