Home > Java > javaTutorial > Kotlin annotation class example tutorial sharing

Kotlin annotation class example tutorial sharing

零下一度
Release: 2017-06-17 11:54:55
Original
1600 people have browsed it

This article mainly introduces the detailed explanation and examples of Kotlin's annotation classes. Friends who need it can refer to

Kotlin's detailed explanations and examples of annotation classes

Annotation declaration

Annotations are a way to attach metadata to your code. To declare an annotation, place the annotation modifier in front of the class:


annotation class Fancy
Copy after login

Additional properties of the annotation can be specified by annotating the annotation class with a meta-annotation:

  1. @Target specifies the possible types of elements that can be annotated with this annotation (class, function, attribute, expression, etc.);

  2. @Retention specifies whether the annotation is stored in the compiled class file and whether it can be visible through reflection at runtime (the default is true);

  3. @Repeatable allows Use the same annotation multiple times on a single element;

  4. @MustBeDocumented specifies that the annotation is part of the public API and should be included in the generated API documentation in the signature of the class or method shown in .

##@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)

@ Retention(AnnotationRetention.SOURCE)
@MustBeDocumented

##annotation class Fancy


Usage

@Fancy class Foo {
  @Fancy fun baz(@Fancy foo: Int): Int {
    return (@Fancy 1)
  }
}
Copy after login

If you need to annotate the main

constructor

of the class, you need to add the constructor keyword in the constructor declaration, and Add an annotation in front of it:

class Foo @Inject constructor(dependency: MyDependency) {
  // ……
}
Copy after login

You can also annotate property accessors:

class Foo {
  var x: MyDependency? = null
    @Inject set
}
Copy after login

Constructor

annotation can have a constructor that accepts parameters.

annotation class Special(val why: String)

@Special("example") class Foo {}
Copy after login

The allowed parameter types are:


    Types corresponding to Java native types (Int, Long, etc.) ;
  1. String

    ;

  2. Class(Foo
  3. ::class

    );

  4. Enum;
  5. Other annotations;
  6. Arrays of the types listed above.

  7. Annotation parameters cannot have nullable types because the JVM does not support storing null as the value of annotation properties.

If an annotation is used as a parameter of another annotation, its name is not prefixed with the @ character:

annotation class ReplaceWith(val expression: String)

annotation class Deprecated(
    val message: String,
    val replaceWith: ReplaceWith = ReplaceWith(""))
@Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))
Copy after login

If you need to specify a class as an annotation For parameters, please use Kotlin classes (KClass). The Kotlin compiler will automatically convert it into a Java class so that Java code can see the annotation and parameters normally.

import kotlin.reflect.KClass

annotation class Ann(val arg1: KClass<*>, val arg2: KClass<out Any?>)

@Ann(String::class, Int::class) class MyClass
Copy after login

Lambda expressions

Annotations can also be used for lambda expressions. They are applied to the invoke() method that generates the lambda expression body. This is useful for frameworks like Quasar, which use annotations for concurrency control.

annotation class Suspendable

val f = @Suspendable { Fiber.sleep(10) }
Copy after login

Annotation usage target

When annotating properties or main constructor

function parameters

, There will be multiple Java elements generated from the corresponding Kotlin element, so there are multiple possible locations for this annotation in the generated Java bytecode. If you want to specify exactly how the annotation should be generated, use the following syntax:

class Example(@field:Ann val foo,  // 标注 Java 字段
       @get:Ann val bar,   // 标注 Java getter
       @param:Ann val quux)  // 标注 Java 构造函数参数
Copy after login

The same syntax can be used to annotate the entire file. To do this, place the annotation with target file at the top level of the file, before the package directive or before all imports (if the file is in the default package):

@file:JvmName("Foo")

package org.jetbrains.demo
Copy after login

If you have multiple annotations for the same goal, you can avoid duplication of goals by adding square brackets after the goal and placing all annotations within the square brackets:

The complete list of supported usage targets for

class Example {
   @set:[Inject VisibleForTesting]
   var collaborator: Collaborator
}
Copy after login

is:

    file
  1. property (annotations with this target are not visible to Java )
  2. field
  3. get (property getter)
  4. set (property setter)
  5. receiver (receiver parameter of extension function or property)
  6. param (constructor parameter)
  7. setparam (property setter parameter)
  8. delegate (field that stores its delegate instance for a delegate property)

  9. To mark the extension function For the receiver parameter, use the following syntax:

fun @receiver:Fancy String.myExtension() { }
Copy after login

If you do not specify a target, the target is selected based on the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:

  • param

  • property

  • field

Java 注解

Java 注解与 Kotlin 100% 兼容:


import org.junit.Test
import org.junit.Assert.*
import org.junit.Rule
import org.junit.rules.*

class Tests {
  // 将 @Rule 注解应用于属性 getter
  @get:Rule val tempFolder = TemporaryFolder()

  @Test fun simple() {
    val f = tempFolder.newFile()
    assertEquals(42, getTheAnswer())
  }
}
Copy after login

因为 Java 编写的注解没有定义参数顺序,所以不能使用常规函数调用 语法来传递参数。相反,你需要使用命名参数语法。


// Java
public @interface Ann {
  int intValue();
  String stringValue();
}
// Kotlin
@Ann(intValue = 1, stringValue = "abc") class C
Copy after login

就像在 Java 中一样,一个特殊的情况是 value 参数;它的值无需显式名称指定。


// Java
public @interface AnnWithValue {
  String value();
}
// Kotlin
@AnnWithValue("abc") class C
Copy after login

如果 Java 中的 value 参数具有数组类型,它会成为 Kotlin 中的一个 vararg 参数:


// Java
public @interface AnnWithArrayValue {
  String[] value();
}
// Kotlin
@AnnWithArrayValue("abc", "foo", "bar") class C
Copy after login

对于具有数组类型的其他参数,你需要显式使用 arrayOf:


// Java
public @interface AnnWithArrayMethod {
  String[] names();
}
// Kotlin
@AnnWithArrayMethod(names = arrayOf("abc", "foo", "bar")) class C
Copy after login

注解实例的值会作为属性暴露给 Kotlin 代码。


// Java
public @interface Ann {
  int value();
}
// Kotlin
fun foo(ann: Ann) {
  val i = ann.value
}
Copy after login

The above is the detailed content of Kotlin annotation class example tutorial sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template