There is such a function
public inline fun <reified W : ListenableWorker> PeriodicWorkRequestBuilder(
repeatInterval: Duration
): PeriodicWorkRequest.Builder {
return PeriodicWorkRequest.Builder(W::class.java, repeatInterval)
}
requires passing in a generic. How do I set this generic through reflection? The following is the pseudocode.
val work = Class.forName("com.demo.work")
PeriodicWorkRequestBuilder<work::class>(1, TimeUnit.HOURS).build()
You cannot set the generic through reflection, because the function does not exist at runtime. The function is an inline function which gets inlined, i.e. every call of the function is replaced by its body.
For instance, when you write
somewhere in your code, the compiled code will not contain a function call of
PeriodicWorkRequestBuilderinline function (which does not exist in the compiled code), but instead there will be byte code that can be decompiled toYou cannot pass in a generic class via reflection into the inline function, because for the inlining, the compiler has to know the exact type at compile-time.
So, if you want to pass in a generic
Classparameter, you cannot use the inline function. But that's not at all necessary, because you can just use the code inside the function, i.e.This manual inlining of an inline function should work in every possible case, because everything inside an inline function has to be accessable everywhere where you could use the inline function. Otherwise, the inlining of the inline function by the compiler would lead to incorrect code.