Skip to Content
Course content

215: Meta-Annotations and Annotation Targets

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once spent an entire afternoon chasing a bug where a custom validation framework was simply ignoring half of the fields in a data class. The code looked perfect. The annotations were there, the reflection logic was sound, and the compiler wasn't complaining. The problem? I had forgotten that in Kotlin, a single line of code in a primary constructor can represent three different things: a constructor parameter, a class field, and a getter method.

annotation class Validated // No target specified

data class UserProfile(
    @Validated val username: String,
    @Validated val email: String
)

// A snippet of the reflection logic that was failing
fun validate(obj: Any) {
    obj::class.members.forEach { member ->
        // This was looking for annotations on the property/getter
        if (member.annotations.any { it is Validated }) {
            println("Validating ${member.name}...")
        }
    }
}

The Ambiguity of Constructor Properties

In the example above, I applied @Validated to username. But because I didn't specify a target, Kotlin didn't know exactly where that annotation should live. Depending on the compiler version and the specific context, it might have been applied to the constructor parameter, but not the actual field or the getter. When my validate function scanned the class members (the properties), it found nothing. The annotation was "invisible" because it was sitting on the constructor parameter, which isn't technically a member of the class.

This is a classic "silent failure." The code compiles because, by default, an annotation with no target can be placed almost anywhere. But in a professional codebase, that's actually a liability. You don't want developers putting a @JsonSerializable annotation on a local variable inside a function; it makes no sense and leads to runtime crashes.

Constraining the Target

To fix this, we use meta-annotations. A meta-annotation is simply an annotation that you apply to another annotation definition. The most important one here is @Target. By using AnnotationTarget, we can tell the compiler exactly where this annotation is allowed to exist.

@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD)
annotation class Validated

Now, if someone tries to put @Validated on a class or a local variable, the IDE will highlight it in red immediately. More importantly, by specifying AnnotationTarget.PROPERTY, we ensure the annotation is associated with the Kotlin property, making it visible to the reflection logic scanning obj::class.members.

You can provide multiple targets by passing them as a comma-separated list. I often do this when I want an annotation to work on both a function and the property that might hold its result.

Controlling the Lifecycle with Retention

While we're talking about meta-annotations, we have to mention @Retention. If you're writing a library or a framework that uses reflection, this is where things usually go sideways. There are three levels of retention:

  • AnnotationRetention.SOURCE: The annotation is discarded by the compiler. It's great for tools like Lint or for providing hints to the IDE, but it doesn't exist in the .class file.
  • AnnotationRetention.BINARY: The annotation is stored in the binary, but it's not visible via reflection at runtime.
  • AnnotationRetention.RUNTIME: The annotation is stored in the binary and can be read by the JVM at runtime.

In Kotlin, the default is RUNTIME, but I always make it explicit. It documents the intent for anyone else reading my code—they'll know immediately that this annotation is intended to be processed by a reflection-based engine.

@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Validated

I've seen developers use SOURCE for things they intended to check at runtime, only to spend hours wondering why member.annotations was returning an empty list. Always double-check your retention if your reflection logic is coming up empty.




📋 Practical Task

Build a Role-Based Access Control (RBAC) Annotation System

You are building a security module for a backend service. Your goal is to create an annotation called @RequiresRole that can only be applied to functions. This annotation should take a String parameter representing the required role (e.g., "ADMIN", "EDITOR").

Requirements:

  • Create the @RequiresRole annotation.
  • Use meta-annotations to ensure it can only be applied to functions (AnnotationTarget.FUNCTION).
  • Set the retention to RUNTIME.
  • Create a class ApiService with two functions: deleteUser() (marked as "ADMIN") and viewDashboard() (marked as "USER").
  • Write a function called checkAccess(service: Any, functionName: String, userRole: String) that uses reflection to:
    1. Find the function by its name within the provided service object.
    2. Check if the @RequiresRole annotation is present.
    3. If present, compare the required role with the userRole.
    4. Print "Access Granted" or "Access Denied".

Bonus Challenge: Try applying @RequiresRole to a class property and observe how the compiler prevents you from doing so.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.