0

I am creating some android app just for fun (it's not really app it's just like sandbox).

For the first time I use reflection for setting some new value in private field of object of Android SDK class.

It looks like this:

try {
    f = obj.getClass().getDeclaredField("<field_name>");
    f.setAccessible(true);
    f.set(obj, <new_value>);
} catch (Exception e) {
    // log
}

I know it's a bad practice for using (and I will change it ASAP), but now it's this way. It works fine on my 3 devices and emulator.

So my question is: In which cases I can not set a new value for existing field?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Igor Tyulkanov
  • 5,487
  • 2
  • 32
  • 49
  • 1
    If you really have to use reflection to modify private members, you should at least make them private again with a `f.setAccessible(false);` call when you're done with it. This being said, I don't think there are limitations to what fields you can modify like this, as long as there isn't a particular JVM policy restricting your rights. – executifs May 19 '14 at 08:13

1 Answers1

0

I followed by sorce codes of Android and came to this file: AccessCheck.c.

dvmCheckFieldAccess method is responsible for throwing an IlligalAccessExceptin. This is what I ask. If a method returns false IlligalAccessExceptin will be thrown.

I think the main thing for this case it is:

if (accessFlags & ACC_PRIVATE)
    return false;

ACC_PRIVATE flag have to same for all Android devices if they use original DVM (Dalvik VM), so it tells us the same thing suggested @executifs. Correct me if I'm wrong.

Igor Tyulkanov
  • 5,487
  • 2
  • 32
  • 49