1

I have data class like this

@Tagme("Response")
@TagResponse
data class Response(
    val id: Int,
    val title: String,
    val label: String,
    val images: List<String>,

    @Input(Parameter::class)
    val slug: Slug
)

Using annotation processor, I was able to get Response properties using this approach:

val parentMetadata = (element as TypeElement).toImmutableKmClass()

parentMetadata.constructors[0].valueParameters.map { prop ->

   // this will loop through class properties and return ImmutableKmValueParameter
   // eg: id, title, label, images, slug.

   // then, I need to get the annotation that property has here.
   // eg: @Input(Parameter::class) on slug property.

   // if prop is slug, this will return true.
   val isAnnotationAvailable = prop.hasAnnotations

   // Here I need to get the annotated value
   // val annotation = [..something..].getAnnotation(Input::class)
   // How to get the annotation? So I can do this:
   if ([prop annotation] has [@Input]) {
      do the something.
   }
}

Previously I tried to get the annotation like this:

val annotations = prop.type?.annotations

But, I got empty list even isAnnotationAvailable value is true

Thanks in advance!

1 Answers1

2

Annotations are only stored in metadata if they have nowhere else they can be stored. For parameters, you must read them directly off of the Parameter (reflection) or VariableElement (elements API). This is why we have the ClassInspector API. You almost never want to try to read anything other than basic class data. Anything that's already contained in the bytecode or elements is basically never duplicated into metadata as well. Treat metadata as added signal, not a wholesale replacement.

Zac Sweers
  • 3,101
  • 2
  • 18
  • 20
  • 1
    There is no `.annotations` on `ImmutableKmValueParameter`. – Dede Adhyatmika Apr 27 '20 at 03:02
  • I found this: https://discuss.kotlinlang.org/t/announcing-kotlinx-metadata-jvm-library-for-reading-modifying-metadata-of-kotlin-jvm-class-files/7980/30?u=ptdede So, we can't read annotation via metadata right? So this is why. So sad. T.T – Dede Adhyatmika Apr 28 '20 at 04:38
  • That comment is about `@file:` annotations, not annotations in general. You're right, I misremembered the API at first. Annotations are only stored in metadata if they have nowhere else they can be stored. For parameters however, you must read them directly off of the Parameter or VariableElement. This is why we have the `ClassInspector` API. I've edited the answer with this as well. – Zac Sweers Apr 28 '20 at 05:02
  • In the end I'm using elements API and it works! Thank you soo much – Dede Adhyatmika Apr 28 '20 at 16:39
  • 1
    Upvoted because, after hours of research, I did not read about this anywhere else. I wonder why this kind of information is not more easily accessible. I guess all Kotlin meta-programming tools are still very new... – m_katsifarakis Oct 20 '20 at 09:22