We can access private variables through the Java reflection API. So then what is the use of having access modifiers? Also help me to get a better understanding of the real usage of access modifiers (private, public, etc.) in real-world applications.
We can access private variables through the Java reflection API. So then what is the use of having access modifiers? Also help me to get a better understanding of the real usage of access modifiers (private, public, etc.) in real-world applications.
It still protects private variables from beeing used wrong by developers. If someone uses reflection to access private variables he (hopefuly) knows what he is doing.
Also most frameworks won't access the variable directly, but instead will look for the getter and setter of the variable.
That "access of private" fields via reflection is not going to be supported for a very long time, eventually it will disappear. With most recent java versions, you already get warnings when you try to access things in a reflective way (like private and protected). In future versions, that might be gone entirely. The JVM becomes more and more encapsulated and restricted in each version, via project jigsaw.
And newer APIs in java, like MethodHandles, that can create/access private members via privateLookupIn will fail if you are not within proper scope. In simpler words - you can access private members of some code, like in a module that allows/exposes such access, but not everywhere. In a way, this is a more restrictive API rather than reflection. So work to block such usages is on the way, via properly crafted newer APIs.
As to the argument that reflections is used by libraries - that is true. But rarely a good library will need private access. Spring, which is the most famous - does not need that information. It only needs public class data (like methods that are public), annotations, etc.