Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of access modifiers if they can be bypassed with reflection?

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.

like image 868
BenLewis Avatar asked Aug 20 '19 14:08

BenLewis


2 Answers

A significant purpose of access modifiers is to structure the code and help users of that code understand and use it effectively and correctly. This is different from serving as a tamper-proof security mechanism. For this reason, it is not contradictory to have both access modifiers and reflection. Writers of the code can express their intent using access modifiers, and code that needs to bypass them, for whatever reason, can do this with the usual risks and implications.

like image 144
SDJ Avatar answered Nov 14 '22 23:11

SDJ


I think the advantages of modifier is that you know much faster how to use a file/library. You can't access private fields/methods without reflection.

For the case you want to prevent attackers to use reflection the JVM has a security mechanism that allows you to define restrictions to code through a Java security policy file. It will use the default one unless you specify otherwise.

Run your application using a SecurityManager and a sufficiently restrictive security policy, policy can be found here.

You may find this tutorial useful: http://docs.oracle.com/javase/tutorial/essential/environment/security.html

like image 23
AndiCover Avatar answered Nov 14 '22 22:11

AndiCover