Kotlin学习手记——注解、注解处理器、编译器插件

本文介绍了Kotlin中的注解、注解处理器和编译器插件的使用,通过示例展示了如何利用注解实现动态API接口,并结合反射和注解处理器进行Model映射。详细讲解了注解的Retention和Target属性,以及如何在运行时和编译时使用注解。此外,还提到了代码生成库JavaPoet和KotlinPoet在注解处理器中的应用。
摘要由CSDN通过智能技术生成

data class User(

var login: String,

var location: String,

var bio: String)

@Retention(AnnotationRetention.RUNTIME)

@Target(AnnotationTarget.CLASS)

annotation class Api(val url: String)

@Retention(AnnotationRetention.RUNTIME)

@Target(AnnotationTarget.CLASS)

annotation class Path(val url: String = “”)

@Retention(AnnotationRetention.RUNTIME)

@Target(AnnotationTarget.FUNCTION)

annotation class Get(val url: String = “”)

@Retention(AnnotationRetention.RUNTIME)

@Target(AnnotationTarget.VALUE_PARAMETER)

annotation class PathVariable(val name: String = “”)

@Retention(AnnotationRetention.RUNTIME)

@Target(AnnotationTarget.VALUE_PARAMETER)

annotation class Query(val name: String = “”)

@Api(“https://api.github.com”)

interface GitHubApi {

@Api(“users”)

interface Users {

@Get(“{name}”)

fun get(name: String): User

@Get(“{name}/followers”)

fun followers(name: String): List

}

@Api(“repos”)

interface Repos {

@Get(“{owner}/{repo}/forks”)

fun forks(owner: String, repo: String)

}

}

object RetroApi {

const val PATH_PATTERN = “”“({(\w+)})”“”

val okHttp = OkHttpClient()

val gson = Gson()

val enclosing = {

cls: Class<*> ->

var currentCls: Class<*>? = cls

sequence {

while(currentCls != null){

// enclosingClass获取下一个class

// yield将对象添加到正在构建的sequence序列当中

currentCls = currentCls?.also { yield(it) }?.enclosingClass

}

}

}

//内联特化

inline fun create(): T {

val functionMap = T::class.functions.map{ it.name to it }.toMap() //【函数名,函数本身】的Pair转成map

val interfaces = enclosing(T::class.java).takeWhile { it.isInterface }.toList() //拿到所有接口列表

println("interfaces= i n t e r f a c e s " ) / / 输出 [ G i t H u b A p i interfaces")// 输出 [GitHubApi interfaces")//输出[GitHubApiUsers, GitHubApi]

//foldRight从interfaces序列的右边开始拼

val apiPath = interfaces.foldRight(StringBuilder()) {

clazz, acc ->

// 拿到每个接口类的Api注解的url参数值,如果url参数为空,则使用类名作为url值

acc.a

  • 24
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值