How to get the class's annotation by reflection

 

import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Retention
import kotlin.reflect.KFunction1

Retention(RetentionPolicy.RUNTIME)
annotation class special(val why: String)

open class Model(val str: String) {
  open fun print() {
  println(str)
  }
}

special(“Mode 1 annotation”)
open class Model1(str: String) : Model(str)

special(“Mode 2 annotation”)
open class Model2(str: String) : Model(str)

class Factory(val func: KFunction1<String, Model>) {
  fun gen(): Model? {

  &nbsp;&nbsp;// Can't get the Model's special annotation, how to get it?
  &nbsp;&nbsp;val str = func.javaClass.getAnnotation(javaClass&lt;special&gt;())?.why?:"error: $func"

  &nbsp;&nbsp;return func.invoke(str)

  }
}

fun main(args: Array<String>) {
  Factory(::Model1).gen()?.print()
  Factory(::Model2).gen()?.print()
}

You're trying to load annotations of an anonymous declaration synthesized for ::ModelN expression, instead of the desired class.

Right now I can only suggest you additionally to pass an instance of Class you’re creating to Factory. In the future func will be a KConstructor and it will be possible to obtain this information from it alone.

 

class Factory(val cls: Class<out Model>) {
  fun gen(): Model? {

  &nbsp;&nbsp;val str = cls.getAnnotation(javaClass&lt;special&gt;())?.why ?: "error: ${cls}"

  &nbsp;&nbsp;return cls.getConstructor(javaClass&lt;String&gt;()).newInstance(str)

  }
}

fun main(args: Array<String>) {
  Factory(javaClass<Model1>()).gen()?.print()
  Factory(javaClass<Model2>()).gen()?.print()
}


I see, Is there a better way?