liveBook · Manning

Annotation class

As explained in Kotlin in Action, 2E

An annotation class is a Kotlin declaration that defines the structure and parameters of an annotation type without containing executable code.

An annotation class defines the structure of metadata attached to declarations or expressions. It contains no executable code, and its parameters describe the values stored with each annotation instance. section 12.0 section 12.1.4

Define parameterless and parameterized annotations

annotation class JsonExclude annotation class JsonName(val name: String) @JsonName("first_name") val firstName: String section 12.1.4

Declare an annotation class with the annotation modifier and a primary constructor. Every constructor parameter must be marked val; omit the class body because annotation classes cannot contain code. section 12.1.4

annotation class JsonName(val name: String)

Use the compact declaration to inspect how an annotation stores a named string parameter. section 12.1.4

Applying a Kotlin annotation behaves like a constructor call: use named arguments when useful, or omit the name for the first parameter. Java annotations follow different conventions, especially around the special value attribute. section 12.1.4

Control how an annotation class is used:

  • Apply @Target to restrict annotations to classes, files, functions, properties, types, expressions, or other supported elements. section 12.1.5
  • Target ANNOTATION_CLASS when defining a meta-annotation that marks other annotation classes. section 12.1.5
  • Use retention-related meta-annotations to control storage in class files and availability through reflection. section 12.1.5
  • Accept class references with KClass when annotation metadata must select an implementation class. section 12.1.6

Store a class reference

annotation class DeserializeInterface(val targetClass: KClass<out Any>) @DeserializeInterface(CompanyImpl::class) val company: Company section 12.1.6

How Kotlin in Action, 2E covers it

How deep it goes
Explains declaration syntax, constructor parameters, Java differences, targets, retention, meta-annotations, and KClass parameters.
Examples
Uses JsonExclude, JsonName, DeserializeInterface, property targets, binding meta-annotations, and CompanyImpl::class.
What you can do after
Builds annotation classes with immutable constructor parameters, controlled targets, retention behavior, and class-reference arguments.
How it connects
Connects annotation classes to metadata, primary constructors, Java annotations, meta-annotations, retention, KClass, and reflection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.