https://kotlinlang.org logo
#reflect
Title
# reflect
c

Colton Idle

03/09/2024, 7:01 AM
Hello. Reflection noob but I'm basically trying to change the value of a static field in a java class. Here's the java class: https://github.com/tink-crypto/tink-java/blob/main/src/main/java/com/google/crypto/tink/CryptoFormat.java Here's my reflection code that fails:
Copy code
val field = CryptoFormat::class.java.getDeclaredField("NON_RAW_PREFIX_SIZE")

     field.isAccessible = true
     
     val modifers = field.javaClass.getDeclaredField("modifiers")
     modifers.isAccessible = true
     modifers.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv())
     
     field.setInt(null, 2000)

     val newValue = CryptoFormat.NON_RAW_PREFIX_SIZE
     println("NON_RAW_PREFIX_SIZE is now: $newValue")
Error:
java.lang.NoSuchFieldException: modifiers
e

ephemient

03/09/2024, 7:38 AM
that's Java reflection, not Kotlin
but basically Java has locked down reflective access to other modules since JPMS
also even if you bypass that, it won't work
Java compiler implicitly inlines
static final
values that follow certain rules (Kotlin makes it explicit with
const
), and this is one of them. so changing the value at runtime does nothing to existing code
K 1
c

Colton Idle

03/09/2024, 7:49 AM
thanks for teaching!
1
k

Klitos Kyriacou

04/23/2024, 10:46 AM
In any case, is this how you get field modifiers? That would work only if the field
NON_RAW_PREFIX_SIZE
was an instance of a class that had a field called
modifiers
. I think you meant to call
getModifiers()
instead.
e

ephemient

04/24/2024, 10:07 AM
I think you're misreading the code. in older versions of Java, it was possible to bypass the
final
modifier in reflection by modifying (via reflection) the reflected
Field
. now you are not allowed to access
java.base
reflectively, so that trick no longer works
👍 1
2 Views