1

I read the following article about reflection in Java:

https://community.oracle.com/docs/DOC-983192

In it, the author describes how to change the values of an object's fields through reflection. He explains how to do it even if the field has private access.

I while back, I read Joshua Block's book: "Effective Java". There, he says that, in order to prevent unsafe access to an object's fields, methods, etc, whenever possible, we should give fields and methods the most restrictive modifier (ie. private whenever possible, public or protected if it is part of the exposed api).

My question is the following:

Why bother designing your classes to not expose sensible information if it can be accessed through reflection anyway?

(Actually, I am asking for the piece of information that I am missing to understand this topic)

  • 3
    Marking a field private or protected goes a long way in letting users of your library or API know how they should use (or not use) that field. It is not just a matter of security. – rmlan Jul 25 '16 at 22:02
  • 8
    Making things private is like putting an insulated cover on an electrical socket: it indicates to people how you want them to use it; but it doesn't stop somebody unscrewing the front and touching the live wires. – Andy Turner Jul 25 '16 at 22:03
  • 2
    It's also possible to use a SecurityManager to prevent reflective modification. See http://stackoverflow.com/questions/7566626/how-to-restrict-developers-to-use-reflection-to-access-private-methods-and-const – dnault Jul 25 '16 at 22:10

1 Answers1

3

For one thing, 'private' is not meant as a security feature. See this similar question. Java has a security system, which is what you should use if you really want that kind of protection.

'private' in OOP is a signal of intent and is part of the contract of your class. By marking a field as 'private', you are stating that if somebody sneaks in and modifies stuff with reflection or something, then all guarantees you make in the rest of your class are no longer valid.

It's kind of like the fine print in the warranty of your TV or other devices - if you start digging around inside the wiring (the private fields, so to speak), then the warranty is void and Samsung or whoever it is won't cover the cost of repairing whatever you may screw up while you're in there.

Community
  • 1
  • 1
Jeutnarg
  • 1,138
  • 1
  • 16
  • 28