Are private members really more “secure” in Java?

后端 未结 8 2896
后悔当初
后悔当初 2021-02-19 03:23

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 legi

相关标签:
8条回答
  • 2021-02-19 03:42

    Btw: reflection in Java actually allows you to override access modifiers of fields of objects. See javadoc and an example.

    0 讨论(0)
  • 2021-02-19 03:43

    I've never heard of it -- in any serious sense -- as a security issue. I mean, decompilers work. You can use them to figure out what's going on inside the bytecode.

    Having private members is a maintainability issue. If I only give you method-level access to my internals, then my only responsibility is to ensure that my API methods continue to work. I'm not locked into using a Double versus a BigDecimal on the insides, so long as my methods continue to return Doubles (for instance).

    0 讨论(0)
  • 2021-02-19 03:50

    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.

    0 讨论(0)
  • 2021-02-19 03:50

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

    0 讨论(0)
  • 2021-02-19 04:00

    Obviously the principles of making everything private where possible only apply if you adhere to the open-closed principle otherwise if people get used to the idea of editing the internals of existing classes instead of extending them they may well change the encapsulation of private member variables be it through making them accessible through mutators and accessors or changing the access modifier.

    0 讨论(0)
  • 2021-02-19 04:01

    As far as security goes, the answer is "not really": determined hackers could get to your private fields and call your private functions with a little bit of reflection; all they need is a JAR with your code in it.

    Although hiding "sensitive" information does not make your class more secure, it makes it (along with systems built from it) a lot more maintainable. So this answer is not an excuse for making all members of your classes public.

    0 讨论(0)
提交回复
热议问题