Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Annotations

Kotlin Annotations

An annotation is a mechanism for attaching metadata to code; it does not affect program logic itself, but can be read by the compiler, frameworks, and annotation processors.

Kotlin annotations can apply both to Kotlin's own declarations and precisely specify where they land on the JVM, such as a field, getter, or setter.

This chapter covers the definition of annotations, meta-annotations, parameter types, use-site targets, and the built-in annotations most commonly used in everyday development.


Defining and Using Annotations

Using annotation class Define an annotation, which can also have constructor parameters.

When using an annotation, put @注解名 before the target declaration; annotations with parameters pass arguments in parentheses.

Example

// Define an annotation: @Target limits where it can be used, @Retention determines whether it can be read at runtime

@Target

(

AnnotationTarget.

CLASS

, AnnotationTarget.

FUNCTION

)

@Retention

(

AnnotationRetention.

RUNTIME

)

@MustBeDocumented

annotation

class

ApiDoc

(

    val author

:

String

,                  

// Required parameter

    val version

:

String

=

"1.0"

,        

// Optional parameter with a default value

    val tags

:

Array

<

String

=

[

]

// Array parameter

)

@ApiDoc

(

author

=

"RUNOOB"

, version

=

"2.2"

, tags

=

[

"collection"

,

"annotation"

]

)

class

SiteService

{

    @ApiDoc

(

author

=

"RUNOOB"

)

    fun listSites

(

)

:

List

<

String

=

listOf

(

"runoob"

,

"RUNOOB"

)

}

fun main

(

)

{

   

// Read runtime annotations via Java reflection; no need to import kotlin-reflect

    val clazz

=

SiteService

::

class

.

java

    val classDoc

=

clazz.

getAnnotation

(

ApiDoc

::

class

.

java

)

    println

(

"Class annotation: author=${classDoc.author}, version=${classDoc.version}, tags=${classDoc.tags.toList()}"

)

   

// Annotations on methods can be read in the same way

    val method

=

clazz.

getDeclaredMethod

(

"listSites"

)

    val methodDoc

=

method.

getAnnotation

(

ApiDoc

::

class

.

java

)

    println

(

"Method annotation: author=${methodDoc.author}, version=${methodDoc.version}"

)

}



类注解:author=RUNOOB, version=2.2, tags=[collection, annotation]

方法注解:author=RUNOOB, version=1.0

Tip:The method annotation only specifies author, so version takes the default value "1.0". If @Retention it is not RUNTIME, reflection cannot read this annotation.


Meta-annotations

Meta-annotations are 'annotations that annotate other annotations'; they determine where an annotation can be used and how long it is retained.

Meta-annotations Purpose Optional values
@Target Restricts which targets an annotation can mark CLASS, FUNCTION, PROPERTY, FIELD, VALUE_PARAMETER, CONSTRUCTOR, EXPRESSION, FILE, etc.
@Retention Determines the phase until which an annotation is retained SOURCE, BINARY (default), RUNTIME
@Repeatable Allows the same annotation to appear multiple times at the same location No parameters; supported since Kotlin 1.6
@MustBeDocumented Includes the annotation in the generated API documentation No parameters

The three retention levels correspond to different visibility scopes; choosing the wrong level will prevent frameworks from reading the annotation.

Retention Level Where It Is Stored Typical use
SOURCE Exists only in source code and is discarded after compilation Compile-time checks, such as @Suppress
BINARY Written into the class file but not readable by reflection Kotlin's default value, for use by annotation processors
RUNTIME Written into the class file and readable by reflection Runtime frameworks, such as serialization and dependency injection

Note:Omitting it in Kotlin @Retention defaults to BINARY, while Java defaults to CLASS; the two behave consistently. To make it readable by reflection, you must explicitly write RUNTIME.


Annotation Parameters

Annotation parameters cannot be arbitrary values; they must be constants that can be determined at compile time.

Allowed types include primitive types, String, KClass, enums, other annotations, and arrays of these types.

Example

// Enum types can also be used as annotation parameters

enum

class

Level

{

LOW, HIGH

}

// Define another annotation for nesting

annotation

class

Author

(

val name

:

String

)

@Target

(

AnnotationTarget.

CLASS

)

@Retention

(

AnnotationRetention.

RUNTIME

)

annotation

class

Config

(

    val count

:

Int,                        

// Primitive type

    val label

:

String

,                    

// String

    val type

:

Level,                      

// Enum

    val target

:

kotlin.

reflect

.

KClass

<*>

,  

// Class literal

    val owner

:

Author,                    

// Another nested annotation

    val aliases

:

Array

<

String

=

[

]

// Array

)

@Config

(

    count

=

2

,

    label

=

"runoob"

,

    type

=

Level.

HIGH

,

    target

=

String

::

class

,

    owner

=

Author

(

"RUNOOB"

)

,

    aliases

=

[

"www.runoob.com"

,

"RUNOOB"

]

)

class

Site

fun main

(

)

{

    val config

=

Site

::

class

.

java

.

getAnnotation

(

Config

::

class

.

java

)

    println

(

"count=${config.count}, label=${config.label}, type=${config.type}"

)

    println

(

"target=${config.target.java.simpleName}, owner=${config.owner.name}"

)

    println

(

"aliases=${config.aliases.toList()}"

)

}



count=2, label=runoob, type=HIGH

target=String, owner=RUNOOB

aliases=[www.runoob.com, RUNOOB]

Restrictions:Annotation parameters cannot be nullable types or arbitrary objects; the values passed must be literals or const val constants, and cannot be computed at runtime.


Use-Site Targets

A Kotlin property produces a field, a getter, and a setter on the JVM; to specify which one an annotation marks, you need a use-site target.

Goals Target Location Example
@file: The whole file; must be written before the package declaration @file:JvmName("RunoobUtils")
@field: The JVM field behind the property @field:Transient
@property: The Kotlin property itself, invisible from the Java side @property:Marker("...")
@get: The property's getter method @get:JvmName("getName")
@set: The property's setter method @set:JvmName("setName")
@param: Constructor parameter @param:Marker("...")
@setparam: The setter's parameter @setparam:Nullable
@receiver: The receiver of an extension function or extension property @receiver:Marker("...")
@delegate: The field that stores the delegate object of a delegated property @delegate:Transient

When no use-site target is written, Kotlin automatically selects by the priority param, property, field.

Example

// Custom annotation allowed on properties, fields, getters, setters, and constructor parameters

@Target

(

    AnnotationTarget.

PROPERTY

,

    AnnotationTarget.

FIELD

,

    AnnotationTarget.

PROPERTY_GETTER

,

    AnnotationTarget.

PROPERTY_SETTER

,

    AnnotationTarget.

VALUE_PARAMETER

)

@Retention

(

AnnotationRetention.

RUNTIME

)

annotation

class

Marker

(

val desc

:

String

)

class

Site

(

    @get

:

Marker

(

"Applied to getter"

)

       

// Mark only the generated getter

    val name

:

String

=

"runoob"

,

    @param

:

Marker

(

"Applied to constructor parameter"

)

     

// The default location for a constructor parameter is param

    val age

:

Int

=

12

)

{

    @field

:

Marker

(

"Applied to JVM field"

)

    @

Transient

                         

// Equivalent to @field:Transient; the field does not participate in serialization

    var cache

:

String

=

""

    @property

:

Marker

(

"Applied to the property itself"

)

   

// The property itself, visible only in Kotlin code

    val host

:

String

=

"www.runoob.com"

}

fun main

(

)

{

    val site

=

Site

(

)

    println

(

"${site.name} / ${site.age} / ${site.host}"

)

   

// Use reflection to verify the annotation really lands on the getter

    val getter

=

Site

::

class

.

java

.

getDeclaredMethod

(

"getName"

)

    println

(

"Annotation on getter: ${getter.getAnnotation(Marker::class.java).desc}"

)

}



runoob / 12 / www.runoob.com

getter 上的注解:作用于 getter

File-level annotations must be placed at the very top of the file, before the package declaration; below is its actual form.

Example

// File path: RunoobUtils.kt

// @file:JvmName changes the class name generated for the whole file after compilation

@file

:

JvmName

(

"RunoobUtils"

)

package

com.runoob.demo

// Top-level functions are placed into the RunoobUtils class; in Java you call RunoobUtils.getHost()

fun getHost

(

)

:

String

=

"www.runoob.com"

Note:@property: The annotated annotation is completely invisible on the Java side because there is no concept of a 'property' on the JVM; if a Java framework needs to read it, use @field: or @get:。


Common Built-in Annotations

The Kotlin standard library and JVM extensions provide many out-of-the-box annotations, introduced below by category.

Annotation Purpose Scope of application
@Deprecated Marks an API as obsolete; you can specify a message, replacement, and level Classes, functions, properties, etc.
@JvmStatic Generates real static methods for companion objects or singleton methods Members of object and companion object
@JvmField Exposes a property as a field without generating getter/setter Non-private properties with a backing field
@JvmOverloads Generates multiple overloads for functions with default parameters Functions, constructors
@JvmName Changes the name seen on the JVM after compilation Functions, property accessors, files
@Synchronized Adds a lock to a method, equivalent to JVM's synchronized Functions, property accessors
@Throws Declares checked exceptions that may be thrown to Java callers Functions, constructors
@OptIn Explicitly opts in to using APIs marked as experimental Classes, functions, expressions

Example

class

SiteUtils

{

    companion object

{

        @JvmStatic                            

// Generate a static method so Java can write SiteUtils.getHost()

        fun getHost

(

)

:

String

=

"www.runoob.com"

        @JvmField                            

// Expose as a static field without generating a getter

        val DEFAULT_NAME

:

String

=

"RUNOOB"

   

}

   

// Generate multiple overloads for functions with default parameters for easier Java calls

    @JvmOverloads

    fun greet

(

name

:

String

=

"runoob"

, times

:

Int

=

1

)

:

String

{

       

return

buildString

{

            repeat

(

times

)

{

append

(

"Hello $name! "

)

}

       

}

.

trim

(

)

   

}

   

// Change the method name seen on the JVM

    @JvmName

(

"runoobGreet"

)

    fun greetRunoob

(

)

:

String

=

"Hello RUNOOB"

   

// Declare a checked exception that Java callers must handle

    @

Throws

(

java.

io

.

IOException

::

class

)

    fun readConfig

(

)

:

String

{

       

if

(

DEFAULT_NAME.

isEmpty

(

)

)

throw

java.

io

.

IOException

(

"Configuration is empty"

)

       

return

DEFAULT_NAME

   

}

}

// The second parameter of @Deprecated gives the replacement, the third determines the warning level

@Deprecated

(

"Please use SiteUtils instead"

, ReplaceWith

(

"SiteUtils()"

)

, DeprecationLevel.

WARNING

)

class

OldSiteUtils

fun main

(

)

{

    val utils

=

SiteUtils

(

)

    println

(

utils.

greet

(

)

)

    println

(

utils.

greet

(

times

=

2

)

)

    println

(

utils.

greetRunoob

(

)

)

    println

(

SiteUtils.

getHost

(

)

)

    println

(

SiteUtils.

DEFAULT_NAME

)

    println

(

utils.

readConfig

(

)

)

}



Hello runoob!

Hello runoob! Hello runoob!

Hello RUNOOB

www.runoob.com

RUNOOB

RUNOOB

@Synchronized and @Volatile Used in concurrency scenarios; they are only valid on the JVM platform.

Example

class

Counter

{

   

private

var count

=

0

    @

Synchronized

                   

// Add a lock to the method to ensure counts are not lost in multithreading

    fun increment

(

)

:

Int

{

        count

++

       

return

count

   

}

    @

Volatile

                       

// Ensure modifications are immediately visible to other threads

    var stopped

:

Boolean

=

false

}

fun main

(

)

{

    val counter

=

Counter

(

)

    println

(

counter.

increment

(

)

)

    println

(

counter.

increment

(

)

)

    counter.

stopped

=

true

    println

(

"stopped=${counter.stopped}"

)

}



1

2

stopped=true

@Repeatable Allows the same annotation to be repeated; since Kotlin 1.6 a container annotation is generated automatically.

Example

// @Repeatable: the same annotation can appear multiple times at the same location

@Repeatable

@Target

(

AnnotationTarget.

CLASS

)

@Retention

(

AnnotationRetention.

RUNTIME

)

annotation

class

Tag

(

val name

:

String

)

@Tag

(

"collection"

)

@Tag

(

"annotation"

)

class

Site

fun main

(

)

{

   

// Kotlin automatically generates a container annotation; the Java side reads all with getAnnotationsByType

    val tags

=

Site

::

class

.

java

.

getAnnotationsByType

(

Tag

::

class

.

java

)

.

map

{

it.

name

}

    println

(

tags

)

}



[collection, annotation]

When using an experimental API, you need to first mark it with @RequiresOptIn and then the caller uses @OptIn to declare consent.

Example

// Mark an experimental API with @RequiresOptIn; both annotations are available since Kotlin 1.4

@RequiresOptIn

(

    message

=

"This is an experimental API and may change in future versions"

,

    level

=

RequiresOptIn.

Level

.

WARNING

)

@Retention

(

AnnotationRetention.

BINARY

)

@Target

(

AnnotationTarget.

FUNCTION

)

annotation

class

ExperimentalSiteApi

@ExperimentalSiteApi

fun fetchSite

(

)

:

String

=

"www.runoob.com"

// The user explicitly declares 'I am aware of the risks and agree to use it'

@OptIn

(

ExperimentalSiteApi

::

class

)

fun main

(

)

{

    println

(

fetchSite

(

)

)

}



www.runoob.com

Tip:If you don't want to write @OptInat every call site, you can add -opt-in=ExperimentalSiteApito the compiler arguments to opt in to the API by default for the whole module.


Annotation Processing: KSP and kapt

Annotations are just metadata; the real work is done by annotation processors, which scan annotations at compile time and generate code.

The Kotlin ecosystem has two solutions: KSP is the officially promoted new approach, while kapt is for compatibility with existing Java annotation processors.

Comparison Item KSP kapt
Full name Kotlin Symbol Processing Kotlin Annotation Processing Tool
Working Method Directly reads Kotlin symbols and the syntax tree First generates Java stub code, then hands it to the Java processor
Compilation Speed fast Slow, with noticeable stub generation overhead
Multi-platform support Supported Not supported, JVM only
Typical Users Room、Moshi、Hilt Legacy projects that depend on Java processors
Current Status Officially promoted; KSP2 released with Kotlin 2.0 In maintenance mode since Kotlin 1.9

To enable KSP in Gradle you only need to add a plugin, then change the annotation processor dependency from kapt to ksp.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

    id

(

"com.google.devtools.ksp"

)

version

"2.2.0-2.0.2"

 

// The KSP version follows the Kotlin version

}

dependencies

{

    implementation

(

"com.google.dagger:hilt-android:2.51"

)

    ksp

(

"com.google.dagger:hilt-android-compiler:2.51"

)

 

// Use ksp instead of kapt

}

// Only fall back to kapt if the annotation processor supports Java only:

// plugins { kotlin("kapt") }

// dependencies { kapt("com.example:processor:1.0") }

Note:KSP and kapt cannot be enabled for the same annotation processor at the same time; when migrating, replace kapt(...) the entire line with ksp(...), and remove the kapt plugin.


Common questions

The following summarizes the most common problems encountered when using annotations.

Problem Reason Solution
Reflection cannot read the annotation The retention level is the default BINARY plus @Retention(AnnotationRetention.RUNTIME)
The annotation cannot be written onto the field The default location falls on property rather than field Explicitly write @field:注解名
Java frameworks cannot read Kotlin property annotations There is no property concept on the JVM Use @get: or @field:
@JvmField error The property is private, override, or delegated Remove private, or use a normal property
Repeated annotation of the same type fails to compile The annotation does not have @Repeatable Add @Repeatable
A warning appears when calling an experimental API The API is marked with @RequiresOptIn Add @OptInat the call site, or configure a compiler argument