Answer the question
In order to leave comments, you need to log in
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;
}
}
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());
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question