Are private members really more “secure” in Java?

2019-04-04 05:57发布

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

标签: java oop
8条回答
乱世女痞
2楼-- · 2019-04-04 06:54

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 bypass private 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).

查看更多
▲ chillily
3楼-- · 2019-04-04 06:55

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 the private access modifier.

查看更多
登录 后发表回答