Since we can access anything with reflection, no matter if it's a field, method or constructor, what does declaring something private really help/do? Is the sole purpose of a private field to tell other programmers that hey, this field isn't intended to be used like this?
While talking about security, is there a way to prevent users from accessing an API's (for the sake of the topic let's say it's closed-source) private and protected fields?
If you allow untrusted code to run in a JVM without a security manager, it can turn off
private
checking viasetAccessible
thus makingprivate
fields and methods available via reflection.Java's
SecurityManager
has a poor history of withstanding determined attacks so it is not reasonable to assume thatSecurityManager
will prevent a determined attacker who can cause arbitrary bytecode to load.Even if the
SecurityManager
holds up, proofs of concept have shown how secrets have been extracted via low-level Java APIs like the serialization API.Can a secret be hidden in a 'safe' java class offering access credentials? lists some of the pitfalls with trying to store sensitive data in fields in a JVM that also runs untrusted code.