Skip to content

Instantly share code, notes, and snippets.

@SupaHam
Last active February 19, 2023 20:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save SupaHam/ce639470462f96df98fc4aefeac4b629 to your computer and use it in GitHub Desktop.
Save SupaHam/ce639470462f96df98fc4aefeac4b629 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
}
@littleGnAl
Copy link

The code does not work because SecretMirror is not interface

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment