当前位置:网站首页>Kotlin annotation declaration and use
Kotlin annotation declaration and use
2022-06-21 17:30:00 【Lighthouse @kuaidao】
Preface
To call a function, you need to know the class of the function , The number of input parameters and parameter types of the function , Annotations and reflection can skip this limitation , Annotations and reflection can write arbitrary class code that is unknown in advance . Annotations can give specific semantics to class libraries , Reflection can analyze the structure of a class at run time .
Declaration and use of annotations
Annotations allow you to put extra Metadata Relate to a declaration , Then the metadata is extracted and used at run time through reflection .
To apply an annotation , With character @ As a name prefix , Put before comments .
@Test
fun add(){
}
You can provide arguments to annotations
@Deprecated("removeAt(index) instead.",ReplaceWith("removeAt(index)"))
fun remove(index:Int){
}
//RelaceWith It's also a note
@Target()
@Retention(BINARY)
@MustBeDocumented
public annotation class ReplaceWith(val expression: String, vararg val imports: String)
Be careful :
The argument type of an annotation can be a basic type 、 character string 、 enumeration 、 Class reference 、 Other annotation classes 、 Array etc. , stay java Annotation classes declared in , Name it value Variable length parameters that are automatically converted on demand , So you don't have to arrayOf Function can provide multiple arguments .
| explain | expression |
|---|---|
| Specify a class as an annotation argument | @CustomAnnotation(MineClass::class) |
| Another annotation is specified as an argument | Uncommented @, for example :ReplaceWith As annotation arguments , Not added @ Prefix |
| Specify an array as an argument | @RequestMapping(path=arrayof(“/foo”,“/bar”)) |
Annotation arguments need to be determined at compile time , Therefore, attributes as annotation arguments need to use const modification , The declaration is at the top of the file or object In .
Annotation target
It is necessary to explain those elements that need annotation , because kotlin A single declaration in the source code corresponds to multiple java Declaring element .
{
var shengming=1
}
Corresponding java
A declarative property 、 One getter, One setter, The template code will be generated automatically at compile time
Use point target declarations Used to describe the element to be annotated , And in the java You only need to add... To fields or functions @Rule Annotation is OK .
@get:Rule
- @get: Use point target
- Rule: Annotated name
class foler{
@get:Rule
val folder=TemporaryFolder()
@Test
fun testDemo(){
...
}
Kotlin Complete support use point A complete list of goals
| Use point target | Introduce |
|---|---|
| property | java Cannot be applied under the annotation of |
| field | Field |
| get | attribute getter |
| set | attribute setter |
| receiver | Receiver parameter properties |
| param | Construct method properties |
| setparam | attribute setter Parameters of |
| delegate | Delegate properties store the fields of the delegate instance |
| file | Classes of top-level functions and properties declared in the file |
kotlin Allows you to annotate arbitrary expressions
Tips: You can control with annotations javaApi Generation
| annotation | explain |
|---|---|
| @volatile | act as java keyword volatile |
| @strictfp | act as java keyword strictfp |
| @JvmName | Change by kotlin Generated java The name of the method or field |
| @JvmStatic | Object declaration or method of associated object , Exposed as java static Static methods |
| @JvmOverloads | Generate multiple overloads with default parameters |
| @JvmField | Apply to properties , Exposed as no accessors public Field |
Declaration notes
// Annotations without parameters
annotation class MineAnnotation
// Comments with parameters
annotation class MineAnnotation(val name:String)
Annotation class has no class body , The compiler also prohibits . Annotation class A structure for metadata associated with declarations and expressions , stay java The same structure is declared in
public @interface MineAnnotation{
String value()
}
java in value stay kotlin and java Will be treated in a special way . When you apply an annotation , Need to provide except value Display names of all specified properties except . and kotli’n You don't need to do this in . Same as normal constructor . If you will java The annotations declared in apply to kotlin in , Must divide value All arguments other than use Named argument method
//Target.java
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */
ElementType[] value();
}
Yuan notes : Controls how an annotation is handled
Yuan notes : Annotations that can be applied to annotation classes are called meta annotations
@Target(AnnotationTarget.PROPERTY)
annotation class JsonExclude
@Target Meta annotations describe the types of elements to which annotations can be applied ,AnnotationTarget Enumeration values list all possible targets where annotations can be applied , If necessary, you can also declare multiple AnnotationTarget The goal is
public enum class AnnotationTarget {
/** Class, interface or object, annotation class is also included */
CLASS,
/** Annotation class only */
ANNOTATION_CLASS,
/** Generic type parameter (unsupported yet) */
TYPE_PARAMETER,
/** Property */
PROPERTY,
/** Field, including property's backing field */
FIELD,
/** Local variable */
LOCAL_VARIABLE,
/** Value parameter of a function or a constructor */
VALUE_PARAMETER,
/** Constructor only (primary or secondary) */
CONSTRUCTOR,
/** Function (constructors are not included) */
FUNCTION,
/** Property getter only */
PROPERTY_GETTER,
/** Property setter only */
PROPERTY_SETTER,
/** Type usage */
TYPE,
/** Any expression */
EXPRESSION,
/** File */
FILE,
/** Type alias */
@SinceKotlin("1.1")
TYPEALIAS
}
How to define your own meta annotations :ANNOTATION_CLASS
@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class myAnnotation
Use
@myAnnotation
annotation class MYBinding
Be careful : PROPERTY Comments are only in kotlin Available in the , If java To be usable in, you need to declare
@Target(AnnotationTarget.FIELD,AnnotationTarget.PROPERTY), about @Retention Annotation to declare whether the annotation will be stored in .class file , Whether the runtime can access it through reflection classes , stay java Will be in .class Reserved but not available at run time , stay kotlin The default value in is in .class Store annotation information in , stay Runtime Keep the note .
Use class as annotation parameter
The usage scenario is to deserialize a nested class , Custom uses that type argument for assignment
class School{
// The name of the school
val schoolName
// The office , Use the class name ::class To reference a class
@DeserializeInterface(xxx::class)
var office:Office
}
An annotated statement
annotation class DeserializeInterface(val targetClass:Kclass<out Any>)
Notice the generic modifier here out Usage of , Represents a relationship that retains subtypes . namely Covariance ,Kclass The types that can be received include Any namely Any Any derived subtype can be used as Kclass Generic types of . If not used out If you modify it , Can only be passed Any As Kclass Generic types of .
Use generic classes for annotation
interface ValueSeriailizer<T>{
fun toJsonValue(value:T):Any?
fun fromJsonValue(jsonValue:Any?):T
}
data class Persion{
@CustomAnnotation(DateSerializer::class)
val date:Date
}
//@CustomAnnotation How to declare
annotaion class CustomAnnotation(val serializerClass:Kclass<ValueSerializer<*>>)
After that, you need to ensure that serializerClass The arguments entered during the call need to implement ValueSerializer Interface class
Kclass<out ValueSerializer<*>>
out Modifier , Indicates that the receiver has received any implementation ValueSerializer Interface , It's not just ValueSerializer::class
ValueSerializer<*> Medium * , You can serialize any value
Here is a general way to write an annotation class that needs to be passed as an argument :
// If YourClassName Has its own argument type , Just use * Instead of
Kclass<out YourClassName>
summary
- java Apply annotation syntax and kotlin It's almost the same
- kotlin Make the target range of the annotation smaller than java More , Including files and expressions
- The parameters of an annotation class can be basic types 、 character string 、 enumeration 、 Class reference 、 Other annotation class instances 、 Or data
- Use point targets to handle kotlin This one declaration produces multiple bytecode elements .var a=1 Corresponding java Three bytecode elements in .
- The annotation class declaration has a main constructor without a class body. All parameters in the constructor are marked as val attribute
- The meta annotation is used to specify the usage point target 、 Retention mode 、 And other annotation features
quote
Kotlin Actual combat Chapter 10 , Comment part
边栏推荐
- Qt5 knowledge: string list qstringlistmodel
- Three color mark removal method
- 很多軟件公司,其實都是“笑話”
- Still using xshell? Try this cool SSH terminal tool, which is very powerful!
- 线段树&树状数组模板
- Oracle JDBC Driver
- Nanjing University static program analyses -- Introduction learning notes
- 【mysql学习笔记14】DQL语句执行顺序
- Android kotlin 类委托 by,by lazy关键
- [MySQL learning notes 17] sorting out common functions
猜你喜欢
随机推荐
数据类型
变量
[ros2 basics] Introduction to navigation2 navigation system
【mysql学习笔记14】DQL语句执行顺序
Kotlin DSL build
程序员进修之路
4. construction [LR (1) analysis table (including construction project specification family)]
新增Razor组件支持代理连接RDP,JumpServer堡垒机v2.23.0发布
MATLAB实现的基于对称TSP问题研究
kotlin 注解声明与使用
Concept drift in machine learning (Apria)
win32com 操作excel
[Error] ‘vector‘ was not declared in this scope
三色标记清除法
Beaucoup de sociétés de logiciels sont en fait des "blagues"
【Leetcode】297. Serialization and deserialization of binary tree (difficult)
Sword finger offer II 089 House theft / Sword finger offer II 090 Ring house theft
rtmp webrtc 协议 openssl 等安装
NLog自定义Target之MQTT
3M mutual aid intelligent contract system development and construction technology








