What is the reason the setAccessible method of the AccessibleObject class has a boolean parameter?

I am very new to Reflection, and I have a doubt:

public void setAccessible(boolean flag) throws SecurityException 

This method has a boolen parameter flag that indicates the new availability of any fields or methods.
For example, if we try to access the private method of a class from outside the class, then we select the method using getDeclaredMethod and set the accessibility to true , so you can call it, for example: method.setAccessible(true);
Now, in what scenario should we use method.setAccessible(false); , for example, it can be used when there is a public method, and we set the accessibility to false. But what is the need? As far as I understand? If there is no use of method.setAccessible(false) , then we can change the method signature as:

 public void setAccessible() throws SecurityException 
+6
source share
3 answers

Scenario: you removed protection from a private field using Field.setAccessible(true), by reading it and returning the field to its original state using Field.setAccessible(false).

+5
source

You probably would never have done setAccessible(false) in your entire life. This is because setAccessible does not permanently change the visibility of a. When you need something like method.setAccessible(true) , you are allowed to make subsequent calls to this method instance, even if the method in the original source is private.

For example, consider the following:

 A.java ******* public class A { private void fun(){ .... } } B.java *********** public class B{ public void someMeth(){ Class clz = A.class; String funMethod = "fun"; Method method = clz.getDeclaredMethod(funMethod); method.setAccessible(true); method.invoke(); //You can do this, perfectly legal; /** but you cannot do this(below), because fun method visibilty has been turned on public only for the method instance obtained above **/ new A().fun(); //wrong, compilation error /**now you may want to re-switch the visibility to of fun() on method instance to private so you can use the below line**/ method.setAccessible(false); /** but doing so doesn't make much effect **/ } 

}

+14
source
 //create class PrivateVarTest { private abc =5; and private getA() {sop()}} import java.lang.reflect.Field; import java.lang.reflect.Method; public class PrivateVariableAcc { public static void main(String[] args) throws Exception { PrivateVarTest myClass = new PrivateVarTest(); Field field1 = myClass.getClass().getDeclaredField("a"); field1.setAccessible(true); System.out.println("This is access the private field-" + field1.get(myClass)); Method mm = myClass.getClass().getDeclaredMethod("getA"); mm.setAccessible(true); System.out.println("This is calling the private method-" + mm.invoke(myClass, null)); } } 
0
source

Source: https://habr.com/ru/post/943680/


All Articles