I'm using some annotations to dynamically set values of fields in classes. Since I want to do this regardless of whether it's public, protected, or private, I am a calling setAccessible(true)
on the Field object every time before calling the set()
method. My question is what kind of impact does the setAccessible()
call have on the field itself?
More specifically, say it is a private field and this set of code calls setAccessible(true)
. If some other place in the code was then to retrieve the same field through reflection, would the field already be accessible? Or does the getDeclaredFields()
and getDeclaredField()
methods return new instances of a Field object each time?
I guess another way of stating the question is if I call setAccessible(true)
, how important is it to set it back to the original value after I'm done?
Best Answer
With
setAccessible()
you change the behavior of theAccessibleObject
, i.e. theField
instance, but not the actual field of the class. Here's the documentation (excerpt):And a runnable example: