0

When accessing a non-visible field or method using reflection, it seems to be a common idiom to restore the original accessibility value after changing it:

Field field = ...
boolean origAccessibility = field.getAccessibility();
field.setAccessibility(true);
try {
  // access field
} finally {
  field.setAccessibility(origAccessibility);
}

I wonder if there is a good reason to restore the original accessibility state. I see the following cases:

  • Compiled code cannot access the field anyway.
  • Code that accesses a non-visible field using reflection would also call setAccessible(true)
  • Code that uses reflection just to query the method's accessibility would potentially get the wrong result anyway, while the try block is executed.

I tend to think that resetting the original state is useless. Am I missing something?

ralfstx
  • 3,893
  • 2
  • 25
  • 41

1 Answers1

3

No, this is not necessary.

All field.setAccessible does is update the single reference you are using to address the field (the one you put in your field local variable). It does not have any lasting effects. The next time someone else calls clazz.getField or whatever, they get a fresh object back (even when talking about the same field).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • In some unit test, I changed some static field with reflection. This override persisted on another classes :s. I will replicate the issue and post a question – JRichardsz Jan 24 '22 at 20:12