N
N
NamerPro2019-07-14 23:29:56
Java
NamerPro, 2019-07-14 23:29:56

What is the meaning of concealment when there is reflection?

Recently I read an article on reflection. And the question arose:
Why do we need hiding through access modifiers and getters and setters, if all this is easily done through reflection?
I'll give you an example.
Here is class A:

public class A
{

private int age = 0;

public void setAge(int age)
{
if((age > 0) & (age < 100)) this.age = age;
}

public int getAge()
{
return this.age;
}

}

The meaning of hiding if I can create an object with an age of 1000 years through reflection and break the program:
public class B
{

public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
A myClass = new A();
Field field = myClass.getClass().getDeclaredField("age");
field.setAccessible(true);
field.set(myClass, 1000);
field.setAccessible(!field.isAccessible());
System.out.println(myClass.getAge());
}

}

It will print 1000. And what is the meaning of such protection? What gives us such a setter and such an access modifier? Private fields are not inherited unless only.
I asked a question on javarush as a comment to the author of an article about reflection, but he has not visited the site for a long time.
Please be as simple as possible. I'm still quite a beginner.
Thanks in advance :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-07-15
@NamerPRO

Hiding in general, and access modifiers in particular, is not about protecting against malicious hackers who break into your code. Access modifiers are needed to prevent inadvertent misuse of objects. In large systems, it can be difficult to keep track that one object out of hundreds, in one of thousands of possible program states, does not violate the invariants of another object. All OOP is needed to reduce the complexity of the code.
And reflection is a backdoor in the JVM. Reflective code is slow and unsafe. On the contrary, it increases the complexity and reduces to zero half of the advantages of the language. Reflection can only be used when developing tools and frameworks. And even so, it is worth striving to reduce the appeal to it.
Figuratively speaking, you do not have to drink and eat, you can also eat through a dropper. But this does not mean that you do not need teeth and 5 meters of intestines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question