注解
原创小于 1 分钟
/**
* 通用注解,既可以修饰类,也可以修饰方法和字段
*/
annotation class Universal(val value: String)
@Universal("Class")
class HelloWorld {
@Universal("Field")
val name = "lixingyun"
@Universal("Method")
fun hello() {
println("lixingyun")
}
}
/**
* 自定义注解,实现API运行时的方法检查
*/
enum class MethodType {
GET, POST
}
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class HttpMethod(val type: MethodType)
interface HttpClient {
val name: String
get() = "/api"
val version: String
get() = "1.0.0"
}
@HttpMethod(MethodType.GET)
class HttpClientImpl : HttpClient {
}
fun geuUserInfo(client: HttpClient) {
// 通过反射获取注解元信息
val annotations = client.javaClass.annotations
val annotation = annotations.find { it is HttpMethod } as? HttpMethod ?: return
println(annotation?.type)
}
fun main() {
// 应用注解
val helloWorld = HelloWorld()
helloWorld.hello()
val client = HttpClientImpl()
geuUserInfo(client)
}
感谢支持
更多内容,请移步《超级个体》。