How can I modify a `private val` inside a companio...
# getting-started
l
How can I modify a
private val
inside a companion object through reflection?
j
...but why?
😄 1
l
Because I inherited a very badly written legacy code base where Unit Tests are resorting to reflection to overwrite Android's
LifecycleOwner
.
And I have to quickly fix the unit tests after a lifecycle library update. I cannot suddenly refactor the whole project.
I read that it has to be done through Java Reflection:
Copy code
val processLifecycleOwner = ProcessLifecycleOwner.get()
    val ownerInstance = processLifecycleOwner::class.java.getDeclaredField("newInstance")
    ownerInstance.isAccessible = true

    Field::class.java.getDeclaredField("modifiers").apply {
        isAccessible = true
        setInt(ownerInstance, ownerInstance.modifiers and Modifier.FINAL.inv())
    }

    ownerInstance.set(processLifecycleOwner, mockLifecycleOwner)
However it gives me:
Copy code
java.lang.NoSuchFieldException: modifiers
e
you cannot do that on newer versions of the JVM
l
Yes, I suppose that's the problem. Thanks!
Anyway, it's a good opportunity to clean up the code instead of fixing the old hack 😉
👍 1