kotlinannotationskotlin-reflect

How to get annotations of a variable in external method using Kotlin?


I'm starting with Kotlin reflection. I need to write a method in Kotlin that would take a variable (in this case lets say of type String) and return all annotations (if any) that are applied to that variable.

fun getAnnotations(variable: String): List<Annotation>{
   //get annotations here
}

Of course that is only possible if annotations are also passed to the method along with variable itself. I wasn't able to find that info in documentation. For my use case, it is not acceptable to send entire user object to getAnnotations method. So I can't use User::class.getDeclaredField. I need a method that can extract annotations from variable.

Looking forward to learning. Thanks

Example:

Class and annotation:

@Target(AnnotationTarget.PROPERTY)
annotation class MyAnnotation()


data class User(

   @MyAnnotation
   val name: String,

   val address: String
   ...
)

Usage:

//user data is fetched and stored in 'user' object
println(getAnnotations(user.name))      //should return @MyAnnotation
println(getAnnotations(user.address))   //should return empty list

Thank you


Solution

  • A value passed around doesn't hold references to annotations because the annotations are not on the value but on something else, on some "static" definition like a class, a property, a file, etc.

    In your case, the annotation is on the property. When you call user.name, you get the value that the property is currently pointing to, not the property itself. If you want to extract the annotation from the property you need a reference to it, which you can get by using ::. To get the annotations on the name property in the User class, you can call:

    User::name.annotations