Dynamic Proxy

It is possible to create a Dynamic Proxy in common (Multiplatform) code?

For Java there is Proxy.newProxyInstance available, but I don’t found any analogue for Kotlin common (Multiplatform). Is there any possibility for runtime class generation?

I never used the Proxy class but AFAIK it heavily depends on reflection which is a feature that is severely restricted on targets other than the JVM. I’m not even sure that it would be possible to implement this properly for targets like JS or native so I’d really be surprised if there was anything that resembles this in MPP.

You should also probably describe the use case. I never used Proxy, but I believe that many of its use-cases could be replaced either by inline classes or by class delegation (maybe I am wrong).

the whole class of “service interface” libraries is the use case (e.g. retrofit). Proxy is the easiest way (and slowest). Code generation is the only alternative (Proxy is also code gen inside) although you can do it in a different ways, e.g. compiler plugin, annotation processor (not very MPP friendly), gradle/maven plugin, separate gen tool.

1 Like

dynamic proxy is impossible in KN as far as i understand

Thanks for your responses.

I developing multiplatfrom library with integrated DI, and in some cases it needed to wrap provided classes to prevent additional code written from client side. It needed to transform returning values with specific type (not primitive).

Performance impact of reflection for it will not be a problem as it commonly invoked once per client: it is a reactive stream, and I need to add specific transformation, which is very common and required because of architecture of framework.

Delegates don’t solves issue as it allows only re-invoke delegate method, in other cases it still needed to write additional code inside delegate.

Dynamic proxy like java’s Proxy.newProxyInstance() are completely solves my requirements, but, as I understand, nothing like this is possible in common code.

Looks like only way is using code generation and some code pre-processor.

I needed the same thing. Ended up writing my own support for it.

Function ‘proxyFor’.

Feel free to use, contribute, update.
I had much trouble with parts of kotlin reflection having bugs.

The lib needs an update to latest version.
But i used it for mpp, jvm and js.