Kotlin注解

注解用于在编译时将元数据附加到类,接口,参数等。 编译器可以在运行时反射注解。可以根据注解值更改数据或程序的含义。

Kotlin 元注解(Meta-annotations)

可以在声明注解时添加元信息。 以下是一些元注解的说明:

注解名称 描述
@Target 它针对可以使用注解进行注解的所有可能类型的元素。
@Retention 它指定注解是否存储在已编译的类文件中,或者是否在运行时通过反射显示。
@Repeatable 此元注解确定注解在单个代码元素上适用两次或更多次。
@MustBeDocumented 此元文档指定注解是公共API的一部分,应包含在类或方法中。

使用注解的示例

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,  
AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)  
@Retention(AnnotationRetention.SOURCE)  
@MustBeDocumented  
annotation class MyClass

声明注解

通过将注解修饰符放在类的前面来声明注解。

annotation class MyClass

注解构造函数

也可以注解类的构造函数。 这是通过为构造函数声明添加构造函数关键字并在它的前面放置注解来完成的。

class MyClass@Inject constructor( dependency: MyDependency){  
//. . .   
}

注解属性访问器

class MyClass{  
var a: MyDependency? = null  
                    @Inject set  
}

使用构造函数作为注解

也可以使用构造函数作为注解,使用构造函数作为注解需要参数。

annotation class MyClass(val why: String)  
@MyClass("parameter") class Foo{  
}

用作注解的参数不能是可空类型,这是因为JVM不支持null作为注解属性的值。也可以使用一个注解作为另一个注解的参数,在这种情况下它不能使用前缀@字符。 例如:

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"))

Kotlin还指定一个类可以使用KClass来获取注解的参数。 Kotlin编译器自动将它转换为java类,这就像通常看到注解和参数。

import kotlin.reflect.KClass  
annotation class MyClass(val arg1: KClass<*>, val arg2: KClass<out Any>)  
@MyClass(String::class, Int::class) class Foo

使用TYPE注解的示例

创建一个java注解接口Ann.java -

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
@Target(ElementType.TYPE)  
@Retention(RetentionPolicy.RUNTIME)  
@interface  Ann{  
    int value();  
}

创建一个使用Ann接口注解的MyClass.kt类。

@Ann(value = 10)  
class MyClass{  

}  
fun main (args: Array<String>){  
    var c = MyClass()  
    var x = c.javaClass.getAnnotation(Ann::class.java)  
    if(x!=null){  
        println("Value:"+x?.value)  
    }  
}

执行上面示例代码,得到以下结果 -

Value: 10

上一篇:Kotlin HashSet类

下一篇:Kotlin反射

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程