Learning Java I was sometimes taught to use the private
access modifier so as not to expose "sensitive information" to other classes, as if this could open a legitimate security hole. But I've never encountered a situation in which restricting member visibility was more than a convenience for modelling a program in an object-oriented fashion.
Are private
fields and functions in Java classes actually more "secure" than otherwise?
EDIT -- Compilation of best answers.
Why private
does not mean "secure":
- decompilers allow static look at bytecode
- reflection library allows runtime access to private members
What private
is good for:
- maintainability of code due to forcing method-level access
- modularity of code by hiding implementation details
I agree in general with the answers so far (i.e. that
private
is really for code hygiene not real security). Various answers have pointed out that you can bypassprivate
using reflection. Note that you can, in turn, disable reflection if you enable a Java SecurityManager. See particularly the ReflectPermission. However, security managers are rarely used (outside the normal browser sandboxing).No, they are not more "secure" in that sense, though some (very poor) books on Java try to explain
private
in that way. If an attacker had the ability to cause arbitrary Java code to be run in your process, all "security" is already gone. And as another answer already mentioned, reflection can bypass theprivate
access modifier.