If I'm on the JVM I can do this:
object Playground {
class DynamicInvocationHandler : InvocationHandler {
@Throws(Throwable::class)
override operator fun invoke(proxy: Any, method: Method, args: Array<Any>): Any {
LOGGER.info("Invoked method: {}", method.name)
return 42
}
companion object {
private val LOGGER = LoggerFactory.getLogger(
DynamicInvocationHandler::class.java)
}
}
@JvmStatic
fun main(args: Array<String>) {
val proxy = Proxy.newProxyInstance(
Playground::class.java.classLoader,
arrayOf<Class<*>>(MutableMap::class.java),
DynamicInvocationHandler()) as MutableMap<String, String>
proxy["foo"] = "bar"
}
}
and running this will print Invoked method: put
. How can I do something like this in a Kotlin common project?
Edit: I'm not trying to use anything from Java in my common module. I know how common projects work. What I'm interested in instead is whether there is a Kotlin-based solution for this or not.
Edit 2: I'm not trying to proxy the Map
class. I'm looking for something like Proxy
in the JDK which I can use to proxy any interface. Sorry for the confusion.