Kotlin annotation class example tutorial sharing
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
Additional properties of the annotation can be specified by annotating the annotation class with a meta-annotation:
@Target specifies the possible types of elements that can be annotated with this annotation (class, function, attribute, expression, etc.);
@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);
@Repeatable allows Use the same annotation multiple times on a single element;
@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
@Fancy class Foo { @Fancy fun baz(@Fancy foo: Int): Int { return (@Fancy 1) } }
If you need to annotate the mainconstructor
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) { // …… }
You can also annotate property accessors:
class Foo { var x: MyDependency? = null @Inject set }
Constructor
annotation can have a constructor that accepts parameters.
annotation class Special(val why: String) @Special("example") class Foo {}
The allowed parameter types are:
- Types corresponding to Java native types (Int, Long, etc.) ;
- String Class(Foo
- ::class Enum;
- Other annotations;
- Arrays of the types listed above.
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"))
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
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) }
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 构造函数参数
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
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 }
is:
- file
- property (annotations with this target are not visible to Java )
- field
- get (property getter)
- set (property setter)
- receiver (receiver parameter of extension function or property)
- param (constructor parameter)
- setparam (property setter parameter)
- delegate (field that stores its delegate instance for a delegate property)
fun @receiver:Fancy String.myExtension() { }
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()) } }
因为 Java 编写的注解没有定义参数顺序,所以不能使用常规函数调用 语法来传递参数。相反,你需要使用命名参数语法。
// Java public @interface Ann { int intValue(); String stringValue(); } // Kotlin @Ann(intValue = 1, stringValue = "abc") class C
就像在 Java 中一样,一个特殊的情况是 value 参数;它的值无需显式名称指定。
// Java public @interface AnnWithValue { String value(); } // Kotlin @AnnWithValue("abc") class C
如果 Java 中的 value 参数具有数组类型,它会成为 Kotlin 中的一个 vararg 参数:
// Java public @interface AnnWithArrayValue { String[] value(); } // Kotlin @AnnWithArrayValue("abc", "foo", "bar") class C
对于具有数组类型的其他参数,你需要显式使用 arrayOf:
// Java public @interface AnnWithArrayMethod { String[] names(); } // Kotlin @AnnWithArrayMethod(names = arrayOf("abc", "foo", "bar")) class C
注解实例的值会作为属性暴露给 Kotlin 代码。
// Java public @interface Ann { int value(); } // Kotlin fun foo(ann: Ann) { val i = ann.value }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

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.

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 "Shared Members" column 】, and finally check all

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.

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.

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.

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
