https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lukasz Kalnik

03/21/2023, 3:27 PM
How can I modify a
private val
inside a companion object through reflection?
j

Joffrey

03/21/2023, 3:27 PM
...but why?
😄 1
l

Lukasz Kalnik

03/21/2023, 3:28 PM
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

ephemient

03/22/2023, 8:36 AM
you cannot do that on newer versions of the JVM
l

Lukasz Kalnik

03/22/2023, 8:39 AM
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
2 Views