0

Consider the following annotation class

@Target(AnnotationTarget.TYPE)
annotation class ML(val size: Int)

By default, the retention policy is RUNTIME, thus this annotation must be accessible through reflection.

Now I have

val a: @ML(2) List<Int> = listOf(1)

which does compile, but, if examined in the debugger, one gets

a::class.annotations.size = 0

What am I doing incorrectly and what is the correct way to annotate types without wrapping things into classes and annotating properties?

Victor Ermolaev
  • 721
  • 1
  • 5
  • 16

1 Answers1

0

The expression you used:

b::class.annotations

Can be used to obtain the annotations on the class returned by b. List is not annotated with anything, so you get no annotations. Given the location where you put the annotation, you actually want to get the annotations for the return type of property b:

::b.returnType.annotations

EDIT: I thought b was a property. What you want to do is impossible, because annotation information isn't stored for local variables on the JVM. See this question: Can I get information about the local variables using Java reflection? (about Java but it's all the same). If b had been a class property or a top-level property, then what I showed would have applied.

Nicolas
  • 6,611
  • 3
  • 29
  • 73