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.
- is there limitation? can access field of
.class
come across? - during code, once set visibility of field lets "public", changed forever or end of context (method, if, for...)? code below
- 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
Post a Comment