Skip to content

Instantly share code, notes, and snippets.

@vlad-kasatkin
Last active February 4, 2020 20:48
Show Gist options
  • Save vlad-kasatkin/ab78a59d629f373b346c86131e373fb5 to your computer and use it in GitHub Desktop.
Save vlad-kasatkin/ab78a59d629f373b346c86131e373fb5 to your computer and use it in GitHub Desktop.
Proxy for suspend calls that checks if generic is one of the arguments
fun createProxy(forTarget: KClass<*>, delegate: SomeType<*>): SomeType<SomeGeneric> {
return Proxy.newProxyInstance(
delegate.javaClass.classLoader,
Array(1) { SomeType::class.java }) { proxy, method, args ->
val hasFailedTypeCheck = args.filterIsInstance<SomeGeneric>().any { !it::class.isSubclassOf(forTarget) }
if (hasFailedTypeCheck) {
throw IllegalStateException()
}
method.kotlinFunction!!.call(delegate, *args)
} as SomeType<SomeGeneric>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment