In Java, at runtime it's possible to access a private field using reflection and also a private nested/inner class using reflection (e.g. see here). Is there any specific technical reason, or any general design philosophy, that explains why Java is like this? I don't know but from reading this it looks like for C#/.NET, at least in some configurations, the same thing is not possible. Does Java also have that flexibility? Are there any JVM implementations where this is not possible?
Of course even if Java didn't allow access to private fields via reflection, you can always write your own runtime to do whatever you like. Or you can modify the binary .jar/.class file and change the access modifiers (I assume this is possible).
So it seems like there are three possibilities the designers of Java had to chose from:
- Allow direct access to private fields...maybe with a warning.
- Do not allow direct access to private fields, but allow access to private fields using reflection.
- Do not allow direct access to private fields and also do not allow access to private fields using reflection. The only way to access the private fields is to change the runtime or modify the binary .jar/.class file offline.
Choosing the middle one seems arbitrary to me...if the goal is to make it as inconvenient as possible, choice 3 is best. If the goal is to not add artificial inconvenience to things that can't be truly prevented anyway, 1 is best.
Is there something about the language or the runtime that informed or forced the decision to take choice 2?