Hello. Reflection noob but I'm basically trying to...
# reflect
c
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
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
thanks for teaching!
1
k
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
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