I understand that using access modifiers is an important practice when writing Java (or most) code, but isn't it effectively made redundant by the fact that you can bypass these modifiers using reflection?
For example, if I want to protect my objects sensitive variables by setting them to private and providing accessor methods, someone can still easily come in and bypass this using reflection, and potentially set unsafe values. Why does Java provide access modifiers, and then a tool to bypass them? It seems it would just be easier to not use either.
–illegal-access
option ispermit
, code in the unnamed module can access these internals via Reflection. In JDK 11, this is still the case. You only get a warning printed on the command line. – Campballjava.lang.reflect.InaccessibleObjectException: Unable to make field protected final java.lang.reflect.Field jdk.internal.reflect.UnsafeFieldAccessorImpl.field accessible: module java.base does not "opens jdk.internal.reflect" to unnamed module @39fb3ab6
With default jvm 11, you can still use reflections to access typical internals of java API, like private fields ofField
class, but other internal classes that are not part of api are not open. – Tallinternal.reflection
module. Perhaps, you mean theinternal.reflection
package within thejava.base
module. As you noted yourself, some artifacts are specially protected, some are even hidden. But this doesn’t change the fact that the general module protection is disabled by default (otherwise, that special protection was not necessary). – Campball