Last active
February 19, 2023 20:16
-
-
Save SupaHam/ce639470462f96df98fc4aefeac4b629 to your computer and use it in GitHub Desktop.
Dynamic Proxies with Kotlin for accessing private classes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
The code does not work because
SecretMirror
is not interface