注解的使用场景
- 提供信息给编译器:编译器可以利用注解来处理一些,比如一些警告信息、错误等
- 编译阶段时处理:利用注解信息来生成一些代码,在kotlin生成代码非常常见,一些内置的注解为了与java API的互操作性,往往借助注解在编译阶段生成一些额外的代码
- 运行时处理:某些注解可以在程序运行时,通过反射机制获取注解信息来处理一些程序逻辑
public enum class Method{ GET, POST } @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class HttpMethod(val method:Method) interface Api{ val name:String val version:String get() = "1.0" } //class ApiGetArticle(override val name: String) :Api{} @HttpMethod(Method.POST) class ApiGetArticle:Api{ override val name: String get() = "/api.articles" } fun fire(api: Api){ //获取所有注解 val annotations = api.javaClass.annotations val method = annotations.find { it is HttpMethod } as? HttpMethod println("通过注解得知该接口需要通过:${method?.method}请求") } fun main(){ fire(ApiGetArticle()) }
Dana.Lee
To:Dana_Lee1016@126.com