0

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()
SageJustus
  • 631
  • 3
  • 9
  • Are you sure `PeriodicWorkRequestBuilder` is as you write as the reifying needs an external parameter to work, I think. – AndrewL Feb 07 '23 at 16:02
  • @AndrewL It's not written by me, it's an android class. So I don't know how to set generics. – SageJustus Feb 08 '23 at 02:25

1 Answers1

0

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

PeriodicWorkRequestBuilder<com.demo.Work>(someDuration).build()

somewhere in your code, the compiled code will not contain a function call of PeriodicWorkRequestBuilder inline function (which does not exist in the compiled code), but instead there will be byte code that can be decompiled to

PeriodicWorkRequest.Builder(com.demo.Work::class.java, someDuration).build()

You 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 Class parameter, 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.

PeriodicWorkRequest.Builder(Class.forName("com.demo.work"), someDuration)

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.

Karsten Gabriel
  • 3,115
  • 6
  • 19