Mark Murphy
05/27/2020, 9:39 PMdev11
, you could call a top-level composable function from a library via reflection by passing in currentComposer
:
val clazz = Class.forName("com.commonsware.jetc.specimen.basics.ActionCheckboxKt")
val demoMethod = clazz.methods.find { it.name == "ActionCheckboxDemo" }
demoMethod?.let {
it.isAccessible = true
it.invoke(null, currentComposer)
}
In this case, ActionCheckboxDemo()
has zero parameters in terms of the way the source is written. But, if you looked at the compiled class file (e.g., via External Libraries in Studio), you would see that the function was rewritten to take a Composer
.
I'm uncertain how to accomplish this in dev12
. If I look at the compiled class file, it claims to take zero parameters. If I try invoke()
, it claims to take 3 parameters. The release notes support the three-parameter signature, though the docs seem to be somewhat mangled:
A Composable function accepting a single parameter is transformed into a function accepting 3 parameters, the additional parameters are the Composer, a ‘key’ integer. a bitmask integer used to propagate metadata through calls.If I change the invocation to
it.invoke(null, currentComposer, 0, 0)
, it runs. But... should I be deriving better values for those integers from somewhere?Leland Richardson [G]
05/27/2020, 10:32 PMkey
parameter will be going away soon. we had to add it in in order to preserve backwards compatibility with some tooling, but right now it isn’t strictly necessary for the runtime itself0
for the changed and default parameters will always be a reasonable value to pass)Mark Murphy
05/27/2020, 10:39 PMYou can find the equivalent code here:Yeah, I figured you had to have some mechanism for this for the
@Preview
support.
I would like us to consider exposing some reflection extension methods as public API that would allow people to do this safely.Developers wanting to invoke composables via reflection is inevitable. Kinda like Thanos. So, having some first-class way of doing it, rather than schlubs like me cobbling together stuff that works but not always, seems like A Really Good Thing.
Leland Richardson [G]
05/27/2020, 10:40 PMMark Murphy
05/27/2020, 10:42 PMLeland Richardson [G]
05/27/2020, 10:43 PMMark Murphy
05/27/2020, 10:53 PM