代码示例:
package com.lyc.myeight.interfaces
interface ZuFang {
fun KanFang()
fun DingJia(int: Int)
fun QianHeTong()
}
package com.lyc.myeight
import android.util.Log
import com.lyc.myeight.interfaces.ZuFang
class Fangdong:ZuFang {
companion object{
val TAG="testlyc"
}
override fun KanFang() {
Log.d(TAG,"kan")
}
override fun DingJia(int: Int) {
Log.d(TAG,"一个月租金: $int")
}
override fun QianHeTong() {
Log.d(TAG,"签合同")
}
}
handler类:
package com.lyc.myeight
import android.util.Log
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
class ZhongJieHandler :InvocationHandler{
private var mTarget:Any?=null
constructor(target: Any){
this.mTarget=target
}
override fun invoke(p0: Any?, p1: Method?, p2: Array<out Any>?): Any? {
Log.d("testlyc", "执行前")
var result:Any?=null
if (p1 != null) {
result = p1.invoke(mTarget, *p2.orEmpty())
}
Log.d("testlyc", "执行后")
return result
}
}
Smart类:
package com.lyc.myeight
import com.lyc.myeight.interfaces.ZuFang
import java.lang.reflect.Proxy
class ZhongJieSmart {
var mzuFang:ZuFang?=null
constructor(zuFang: ZuFang){
this.mzuFang=zuFang
mzuFang=Proxy.newProxyInstance(
zuFang.javaClass.classLoader,
arrayOf(ZuFang::class.java),
ZhongJieHandler(mzuFang!!)
) as ZuFang
}
}
运行结果:
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行前 2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: kan 2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行后 2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行前 2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 一个月租金: 300 2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行后 2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 执行前 2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 签合同 2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 执行后
|