Java: Accessing private field via reflection (behaviour) -


junior in java; using reflection possible access private fields (not asking how, question 1 , question 2) ok.

my questions related nature of behaviour.

  1. is there limitation? can access field of .class come across?
  2. during code, once set visibility of field lets "public", changed forever or end of context (method, if, for...)? code below
  3. is ok everybody? mean, seniors programmers of stackoverflow, security breach?

code [edited]:

  field f = obj.getclass().getdeclaredfield("field");    if (...) {      f.setaccessible(true);      // f accesible   }   // f accesible? 

is there limitation?

yes - need several jvm permissions (most notably accessdeclaredmembers , suppressaccesschecks, marked big, bold warnings in docs) work; if jvm's security profile strict (say, much-maligned applets), code not work because these permissions not available.

does changed forever?

yes, long program keeps on running fields remain accessible (as long keep on using same field instance changed access permissions).

is bad?

not necessarily. allows java code serialize , de-serialize objects private fields, allows complex mocking may simplify testing, allows peek places not otherwise able peek into. however, since breaks expectations, should use sparingly , make sure users know require permissions , "are looking under hood". docs (see above) state quite considered risky, , should allowed if know doing.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -