CodeBlanks Logo Icon CodeBlanks

Annotations

Learn to read annotations with reflection.

Annotations and reading

An annotation adds metadata to code. @Target specifies where it can be placed. Reflection can read annotations.

Example: @Target(AnnotationTarget.PROPERTY) annotation class Label. A property is marked with @Label. prop.annotations gives the list; prop.findAnnotation<Label>() finds a specific one. This pattern branches on metadata at runtime.

Searching with findAnnotation

findAnnotation<T>() searches for a specific annotation on an element. If found, it returns the annotation; otherwise null.

Example: val label = prop.findAnnotation<Label>(). If @Label is on prop, label is non-null; otherwise it is null. This pattern is a clean way to branch on annotation presence.

Practice Define and read the Label annotation

Define @Target(AnnotationTarget.PROPERTY) annotation class Label. Write class Item(@Label val name: String). In main take the reference val prop = Item::name and call println(prop.annotations.any { it is Label }).

Starter code

Main.kt
// Label annotation: PROPERTY target
// Item class: name property has @Label
// in main take prop, search annotations for Label and print

Sample solution

Main.kt
@Target(AnnotationTarget.PROPERTY)
annotation class Label

class Item(@Label val name: String)

fun main() {
    val prop = Item::name
    println(prop.annotations.any { it is Label })
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the annotation class definition

Question
____ class Label
Answer
annotation class Label

Explanation: annotation class Label declares an annotation.

2 Match the annotation parts

Term Meaning
@Target(...) Placement
annotation class Declaration
@Label Usage
findAnnotation<Label>() Search

3 Which property reads annotations on a property?

  • .methods
  • .fields
  • .constructors
  • .annotations Correct answer

Explanation: annotations gives the annotation list.

All lessons in Advanced