Reading annotations


#1

What do I need to do to get the following program to type check? ([Test] is a regular Java RUNTIME annotation):

/uploads/kotlinlang/original/1X/5f843758ba78955444592bd66eeb146fe29e4fde.png
/uploads/kotlinlang/original/1X/cbca6d8e2c031c66575504d14e6033aecd9fca3c.png


#2

Unfortunately, there are two compiler bug which disallow writing such code: first, annotations are not considered as subtypes of java.lang.annotation.Annotation (KT-1620); second, AssertionError fails when you try to invoke Method.getAnnotation() even with argument of Class<Annotation> type (KT-1621).

As a temporary workaround, you can iterate over a method.getAnnotations() result and check annotation by its class.

import java.lang.annotation.Annotation import annotations.Test

class Hello {
  [Test]
  fun foo() {
  val klass = Hello().javaClass
  val method = klass.getMethod(“foo”, null)
  for (ann in method.sure().getAnnotations()) {
           if (ann.javaClass.getName() == “annotations.Test”) {
           // found!
           }
  }
  println(“Test”)
  }
}