What is the use of having private properties if you can change them with reflection?

I know this sounds silly, but how secure is your API if you can access private properties and change them?

+4
source share
7 answers

What is the point of having locks on your door when people can just hit the door? Using reflection requires more skill and effort. For the most part, the code is fine. In any case, reflection does not work in incompletely trusted environments.

+10
source

In a language that does not support reflection, there is always the possibility of bypassing the API through direct memory access.

Encapsulation is not to protect your API from misuse, but to hide parts of the code that are subject to change. If the client code uses the official interface, it will continue to work after such a change. If not, the author of this code just shot with his foot.

+6
source

Well, at least in .NET you can reject reflection using . NET

In addition, the goal of visibility levels in classes and class members is not only access security. It’s also a tool for organizing and documenting your code: when you see a private member, you know that it is not intended to be used outside the class, and perhaps you can use it with reflection, you usually won’t do it lead to unexpected behavior in your application.

In any case, I find this question similar to: "What is the purpose of doors with locks if I can break them with a large enough hammer?" :-)

+4
source

That's right, it's not entirely safe, but reflection can also be extremely useful. But you can still set the property only if it has a setter, so it’s not all bad.

+1
source

Although reflection is indeed very useful, it considered an indirect method of changing properties, and not, of course, a method that should be approved or supported by your API.

Saying that setting a private property guarantees that it will not be changed by those who access it using normal means

+1
source

The use of private properties is reflected in the same way as without it, but if we take into account the use of a reflex to access private members in a third-party class, he must be sure that he knows what he is doing, and he is sure that this can disrupt performance.

+1
source

You can restrict access to private properties by installing SecurityManager . Therefore, if you need it, you can make it private (and pay the price: some third-party libraries will no longer work).

Similar laws, private are the price tag. They say: "If you do not follow the rules that I impose, a price will be paid." This does not mean that you must follow the rules (just like the prohibition of killing people does not stop killing).

+1
source

All Articles