actor-kotlin

actor-kotlin

Java 动态伪代理,它使用伪装者接口为对象创建代理。(Java dynamic pseudo proxy, which uses the stand-in interface to create a proxy for the object.)

class A {
  fun call(data: String) {
    ...
  }
}
interface B {
  fun call(data: String)
}

interface C {
  fun call(data: Any)
}
B 和 C 都是 A 的伪装者接口

纯Kotlin开发,使用简单但功能强大,可用于组件化开发或插件化项目开发(以目前kotlin反射的速度,还是无法做到工业级,但是仍可做后台服务,一些对耗时操作不敏感的项目。也希望下个版本的kotlin能够在反射层面做些改进吧,目前可以说90%以上的人都在吐槽kotlin反射第一次运行慢的一批)。

Android Demo:
https://github.com/xuehuiniaoyu/actor-demo
https://github.com/xuehuiniaoyu/actor-demo-componentization

项目:
https://github.com/xuehuiniaoyu/actor-kotlin

implementation 'io.github.xuehuiniaoyu:actor-kotlin:2.0.2'
1. ActorBean

ActorBean:对象反射工具,不仅有get/set方法,还能把对象抽象到接口,方便集成。

data class Student(val name: String, var studentStatus: String? = null)

1.1. 直接获取属性值

val student = Student("张三")
val actorStudent = ActorBean(student)
val name = actorStudent("name")

1.2. 通过接口获取属性值

Interface StudentProxy {
    @GET("name") fun getName()
}

val actorStudent = ActorBean(student).agent(StudentProxy::class.java)
val name = actorStudent.getName()

1.3. 直接赋值

val actorStudent = ActorBean(student)
actorStudent.set("studentStatus", "学籍")

1.4. 通过接口给属性赋值


Interface StudentProxy {
    @SET("studentStatus") fun setStudentStatus(status: String)
}

val actorStudent = ActorBean(student).agent(StudentProxy::class.java)
actorStudent.setStudentStatus("学籍")
2. ActorInterface

ActorInterface 接口动态伪装工具,通过Interface2伪装成Interface1

interface Interface1 {
    fun log(log: String)
}

interface Interface2 {
    fun log(log: Any)
}
val actorInterface = ActorInterface(object: Interface2 {
    override fun log(log: Any) {
        println("log: $log")
    }
})

actorInterface.getImplement<Interface1> { impl ->
    impl?.log("hello world!")
}
actorInterface.bindInterface(Interface1::class.java)
actorInterface.recovery()
3. @DynamicImplementation

表示:伪装类需要动态实现




以上都是对工具类的介绍,Actor才是主角,Actor内部整合了ActorInterface和@DynamicImplementation,看下如何实现:
interface Interface1 {
    fun log(log: String)
}

interface Interface2 {
    fun log(log: Any)
}
class Kit {
    fun call(key: String, interface1: Interface1) {
        interface1.log("$key -------> hello world from call...")
    }
}
interface KitProxy {
    fun call(key: String, @DynamicImplementation data: Any)
}

利用Actor让KitProxy伪装成Kit对象

val callback = object: Interface2 {
    override fun log(log: Any) {
        println("log: $log")
    }
}

val proxy = Actor(Kit()).imitator(KitProxy::class.java)
proxy.call("hello", callback)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值