5

我在反射方面很新,我有一个疑问:

public void setAccessible(boolean flag) throws SecurityException

此方法有一个boolen参数标志,它指示任何字段或方法的新可访问性。
例如,如果我们尝试private从类外部访问类的方法,那么我们使用获取方法getDeclaredMethod并将可访问性设置为true,因此可以调用它,例如:method.setAccessible(true);
现在我们应该在哪种情况下使用method.setAccessible(false);,例如当有public方法并且我们将可访问性设置为false时可以使用。但那有什么需要呢?我的理解清楚吗?
如果没有使用,method.setAccessible(false)那么我们可以更改方法签名,如:

public void setAccessible() throws SecurityException
4

3 回答 3

18

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

  }

}

于 2013-04-26T07:29:46.740 回答
4

场景:您从私有字段中删除保护并Field.setAccessible(true),读取它并将该字段恢复为原始状态Field.setAccessible(false).

于 2013-04-26T07:11:22.317 回答
0
//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));

}

}
于 2013-11-23T09:49:28.340 回答