Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: changing private static final field using java reflection

Change private static final field using Java reflection

I followed the instructions in the link above to change a private static final field using java reflection. I have an object named "data." Inside "data," there is a private static final variable named "type." I want to set "type" to be null. Here is my code.

Field field = data.getClass().getDeclaredField("type");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(data, null);

I tried doing this on Java 1.7 with similar code and it worked. But running this code on Android produces the following error: java.lang.NoSuchFieldException: modifiers

I guess "modifiers" is not a field in the Field class on Android.

How do I fix this?

like image 578
jas7 Avatar asked Jun 25 '12 07:06

jas7


People also ask

How do I change the value of the final static variable in Java?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.

How do you set up a private field in a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Can static final variables be changed?

Finally, with the static final variable, it's both the same for each class and it can't be changed after it's initialized.

Can final fields be changed?

final fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then the final fields of the object are updated.


1 Answers

This works for non-static fields.

Field field = data.getClass().getDeclaredField("type");
field.setAccessible(true);
field.set(data, null);
like image 163
jas7 Avatar answered Oct 19 '22 14:10

jas7