注解用于在编译时将元数据附加到类,接口,参数等。注解可以由编译器使用,它会在运行时反射出来。无涯教程可以根据注解值更改数据或程序的含义。
无涯教程可以在声明注解时添加元信息。
注解名称 | 使用 |
---|---|
@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
也可以注解类的构造函数。这是通过为构造函数声明添加constructor关键字并将注解放在其前面来完成的。
class MyClass@Inject constructor( dependency: MyDependency){ //. . . }
class MyClass{ var a: MyDependency? = null @Inject set }
无涯教程还可以使用构造函数作为注解。使用构造函数作为批注需要参数。
annotation class MyClass(val why: String) @MyClass("parameter") class Foo{ }
用作注解的参数不能为可为null的类型。这是因为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接受注解的自变量。
import kotlin.reflect.KClass annotation class MyClass(val arg1: KClass<*>, val arg2: KClass<out Any>) @MyClass(String::class, Int::class) class Foo
创建一个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){ var c = MyClass() var x = c.javaClass.getAnnotation(Ann::class.java) if(x!=null){ println("Value:"+x?.value) } }
输出:
Value: 10
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)