Java AccessibleObject setAccessible()方法

java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject[] array, boolean flag)方法是通过单个安全检查(效率)来设置对象数组的可访问标志的便利方法。

1 语法

public static void setAccessible(AccessibleObject[] array, boolean flag) 
   throws SecurityException

2 参数

array : AccessibleObjects的数组。

flag : 每个对象中可访问标志的新值。

3 返回值

如果此元素上存在指定注解类型的注解则为true,否则为false。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java AccessibleObject setAccessible()方法
 */
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleField = SampleClass.class.getDeclaredField("sampleField");
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());

      AccessibleObject[] array = new AccessibleObject[1];
      array[0] = sampleField;

      AccessibleObject.setAccessible(array, true);
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());
   }
}

@CustomAnnotation(name="SampleClass",  value = "Sample Class Annotation")
class SampleClass {
   private String sampleField;

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}

输出结果为:

sampleField.isAccessible: false
sampleField.isAccessible: true

 

热门文章

优秀文章