Junior in Java; using reflection is possible to access private fields (not asking how, Question 1 and Question 2) Ok.
My questions are related with the nature of this behaviour.
.class I come across?Code [EDITED]:
Field f = obj.getClass().getDeclaredField("field");
if (...) {
f.setAccessible(true);
// f IS accesible
}
// is f accesible?
Is there any limitation?
Yes - you need several JVM permissions (most notably accessDeclaredMembers and suppressAccessChecks, marked with big, bold warnings in the docs) for this to work; if your JVM's security profile is somewhat strict (say, the much-maligned applets), your code will not work because these permissions will not be available.
Does it get changed forever?
Yes, as long as your program keeps on running the fields will remain accessible (as long as you keep on using the same Field instance where you changed access permissions).
Is it bad?
Not necessarily. It allows java code to serialize and de-serialize objects with private fields, it allows complex mocking that may simplify testing, it allows you to peek into places you would not otherwise be able to peek into. However, since it breaks expectations, you should use it sparingly and make sure that users know that you require the extra permissions and "are looking under the hood". The docs (see above) state quite clearly that this is considered risky, and that it should only be allowed if you know what you are doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With