JAVA反射之取消對訪問控制檢查

package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * AccessibleObject類是Field、Method、和Constructor對象的基類。它提供了將反射的對象標記爲在使用時取消默認Java
 * 語言訪問控制檢查的能力。對於公共成員、默認(打包)訪問成員、受保護成員和私有成員,在分別使用Field、Method和
 * Constructor對象來設置或獲得字段、調用方法,或者創建和初始化類的新實例的時候,會執行訪問檢查。
 * 
 * 當反射對象的accessible標誌設爲true時,則表示反射的對象在使用時應該取消Java語言訪問檢查。反之則檢查。由於
 * JDK的安全檢查耗時較多,所以通過setAccessible(true)的方式關閉安全檢查來提升反射速度
 * @author user
 *
 */
public class ReflectTest {

	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
		Person person = new Person();
		Class<?> personType = person.getClass();
		//getDeclaredMethod可以獲取到所有方法,而getMethod只能獲取public  
		Field field = personType.getDeclaredField("name");
		//取消對訪問控制修飾符的檢查
		field.setAccessible(true);
		field.set(person, " ZHANG SAN ");
		System.out.println("The value of the Field is : " + person.getName());
		
		Method method = personType.getDeclaredMethod("say", String.class);
		method.setAccessible(true);
		method.invoke(person, "Hello World!");
		
	}
}
class Person{
	private String name;
	
	public Person(){};
	
	public String getName(){
		return name;
	}
	
	private void say(String message){
		System.out.println("Name:"+name+"; say:"+message);
	}
}

發佈了43 篇原創文章 · 獲贊 168 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章