Java: accessing a private field via reflection (behavior)

Junior in Java; using reflection it is possible to access private fields (without asking how, Question 1 and Question 2 ) Okay.

My questions are related to the nature of this behavior.

  • Are there any restrictions? Can I access any field of anyone .class

    I come across?
  • During my code, once you set the visibility of the field to say "public", is it changed forever or just until the end of the context (method, if, for ...)? Code below
  • Is this normal for everyone? I mean, senior StackOverflow programmers, is this a security breach?

[EDITED] code:

  Field f = obj.getClass().getDeclaredField("field"); 
  if (...) {
     f.setAccessible(true);
     // f IS accesible
  }
  // is f accesible?

      

+3


source to share


1 answer


Are there any restrictions?

Yes - you need multiple JVM permissions (most prominently accessDeclaredMembers

and suppressAccessChecks

marked with big, bold warnings in the docs) for this to work; if your JVM security profile is somewhat strict (say multitasking applets), your code won't work because those permissions won't be available.

Will it be changed forever?



Yes, as long as your program continues to run, the fields will remain available (if you continue to use the same instance Field

where you changed the permissions).

Is it bad?

Not necessary. It allows java code to serialize and de-serialize objects with private fields, which allows for sophisticated mockery that can make testing easier, it lets you look into places you might not otherwise be able to look into. However, since it violates expectations, you should use it sparingly and make sure users know you need additional 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.

+3


source







All Articles