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

11,596

Solution 1

Scenario: you removed protection from a private field with Field.setAccessible(true), read it and returned the field into original state with Field.setAccessible(false).

Solution 2

Probably you would never do setAccessible(false) in your entire life. This is because setAccessible doesn't the change the visiblity of the a member permanently. When you to something like method.setAccessible(true) you are allowed to make subsequent calls on this method instance even if the method in the original source is private.

For example consider this:

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's 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 **/

  }

}

Share:
11,596
Shreyos Adikari
Author by

Shreyos Adikari

Hi All,This is Shreyos from Kolkata,India. I am a java developer. profile for Shreyos Adikari on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/446042.png My meta account.

Updated on June 21, 2022

Comments

  • Shreyos Adikari
    Shreyos Adikari almost 2 years

    I am very new in Reflection and I have a doubt like:

    public void setAccessible(boolean flag) throws SecurityException
    

    This method has a boolen parameter flag, which indicates the new accessibility of any fields or methods.
    For an example if we are try to access a private method of a class from outside the class then we fetch the method using getDeclaredMethod and set the accessibility as true, so it can be invoked, like: method.setAccessible(true);
    Now in which scenario we should use method.setAccessible(false); , for an example it can be used when there is a public method and we set the accessibility as false. But what is the need of that? Is my understanding clear?
    If there is no use of method.setAccessible(false) then we can change the method signature like:

    public void setAccessible() throws SecurityException