Skip to content

Instantly share code, notes, and snippets.

@andrewmcnamara
Forked from SupaHam/DynamicProxies.kt
Created February 19, 2023 20:16
Show Gist options
  • Save andrewmcnamara/f7d82a47a82afd705b59bfec013af899 to your computer and use it in GitHub Desktop.
Save andrewmcnamara/f7d82a47a82afd705b59bfec013af899 to your computer and use it in GitHub Desktop.
Dynamic Proxies with Kotlin for accessing private classes.
/*
* Code by @vmironov on Kotlinlang slack.
*
* This code uses dynamic proxies in Java to make it easier to access inaccessible classes via an accessible representation.
*/
inline fun <reified T : Any> createMirror(value: Any) = createMirror(value, T::class.java)
fun <T> createMirror(value: Any, clazz: Class<T>): T {
val loader = clazz.classLoader
val interfaces = arrayOf(clazz)
return clazz.cast(Proxy.newProxyInstance(loader, interfaces) { proxy, method, args ->
val field = value.javaClass.getDeclaredField(method.name)
val accessible = field.isAccessible
field.isAccessible = true
field.get(value)
field.isAccessible = accessible
})
}
fun main(args: Array<String>) {
val object: Any = Secret("Hello", "Secret")
val mirror: SecretMirror = createMirror<SecretMirror>(object)
// Above `object` is a given object accessed by other means with the type of Any (or Object in Java).
// That object is then passed to createMirror and told to create a representation of `object` via
// the SecretMirror class.
}
data class Secret(
private val foo: String,
private val bar: String
)
class SecretMirror {
fun foo(): String
fun bar(): String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment