Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Accessing private field via reflection (behaviour)

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.

  1. Is there any limitation? Can I access any field of any .class I come across?
  2. During my code, once you set the visibility of a field to lets say "public", is it changed forever or just up to the end of the context (method, if, for...)? Code below
  3. Is it ok for everybody? I mean, Seniors programmers of StackOverflow, is it a security breach?

Code [EDITED]:

  Field f = obj.getClass().getDeclaredField("field"); 
  if (...) {
     f.setAccessible(true);
     // f IS accesible
  }
  // is f accesible?
like image 575
Manu Avatar asked Jun 27 '26 05:06

Manu


1 Answers

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.

like image 165
tucuxi Avatar answered Jun 28 '26 17:06

tucuxi