vendredi 23 septembre 2022

Why I cannot change static final int field with reflection from kotlin android

I have following java class with static final int which I need to change via reflection:

class DateValidator {
   public static final int DIFF = 20;
}

And from Android Kotlin I try to change it value from 20 to 100:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        println("@@@@DateValidator.DIFF: ${DateValidator.DIFF}")
        val clazz = DateValidator::class.java
        println("@@@clazz: $clazz")
        val field: Field = clazz.getDeclaredField("DIFF")
        println("@@@field: $field")
        println("@@@field.isAccessible: ${field.isAccessible}")
        field.isAccessible = true
        println("@@@field.isAccessible2: ${field.isAccessible}")
        val fieldAccessFlags: Field = Field::class.java.getDeclaredField("accessFlags")
        println("@@@fieldAccessFlags: $fieldAccessFlags")
        println("@@@fieldAccessFlags.isAccessible: ${fieldAccessFlags.isAccessible}")
        fieldAccessFlags.isAccessible = true
        println("@@@fieldAccessFlags.isAccessible2: ${fieldAccessFlags.isAccessible}")
        fieldAccessFlags.setInt(field, field.modifiers and Modifier.FINAL.inv())
        field.set(null, 100)
        println("@@@@DateValidator.DIFF2: ${DateValidator.DIFF}")
        field.setInt(null, 100)
        println("@@@@DateValidator.DIFF3: ${DateValidator.DIFF}")

    }

And I have following output in Logcat:

@@@@DateValidator.DIFF: 20
@@@clazz: class com.droiddevstar.changestaticprj.DateValidator
@@@field: public static final int com.droiddevstar.changestaticprj.DateValidator.DIFF
@@@field.isAccessible: false
@@@field.isAccessible2: true
@@@fieldAccessFlags: private int java.lang.reflect.Field.accessFlags
@@@fieldAccessFlags.isAccessible: false
@@@fieldAccessFlags.isAccessible2: true
@@@@DateValidator.DIFF2: 20
@@@@DateValidator.DIFF3: 20

Perhapse reflection doesn't work with primitive int?





Aucun commentaire:

Enregistrer un commentaire