Home Java javaTutorial Kotlin annotation class example tutorial sharing

Kotlin annotation class example tutorial sharing

Jun 17, 2017 am 11:54 AM
kotlin share Example Tutorial annotation

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

How are annotations used for test methods in the JUnit framework? How are annotations used for test methods in the JUnit framework? May 06, 2024 pm 05:33 PM

Annotations in the JUnit framework are used to declare and configure test methods. The main annotations include: @Test (declaration of test methods), @Before (method run before the test method is executed), @After (method run after the test method is executed), @ BeforeClass (method that runs before all test methods are executed), @AfterClass (method that runs after all test methods are executed), these annotations help organize and simplify the test code, and improve the reliability of the test code by providing clear intentions and configurations. Readability and maintainability.

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

See all articles