39 lines
977 B
Kotlin
39 lines
977 B
Kotlin
package util.active
|
|
|
|
import java.lang.reflect.InvocationHandler
|
|
import java.lang.reflect.Method
|
|
import java.lang.reflect.Proxy
|
|
import java.util.concurrent.LinkedBlockingQueue
|
|
|
|
class ActiveObjectHandler(private val target: Any) : InvocationHandler {
|
|
private val queue = LinkedBlockingQueue<Call>()
|
|
|
|
init {
|
|
Thread {
|
|
while (true)
|
|
queue.take().executeOn(target)
|
|
}.start()
|
|
}
|
|
|
|
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {
|
|
if (method != null && args != null)
|
|
queue.add(Call(method, args))
|
|
|
|
return Unit
|
|
}
|
|
|
|
data class Call(val method: Method, val args: Array<out Any>) {
|
|
fun executeOn(target: Any) {
|
|
method.invoke(target, *args)
|
|
}
|
|
}
|
|
}
|
|
|
|
fun <T> Any.toActive(inter: Class<T>): T {
|
|
return Proxy.newProxyInstance(
|
|
this::class.java.classLoader,
|
|
arrayOf(inter),
|
|
ActiveObjectHandler(this)
|
|
) as T
|
|
}
|