AccessibleObject類是Field、Method、和Constructor對象的基類。它提供了將反射的對象標記為在使用時取消默認Java語言訪問控制檢查的能力。對於公共成員、默認(打包)訪問成員、受保護成員和私有成員,在分別使用Field、Method和Constructor對象來設置或獲得字段、調用方法,或者創建和初始化類的新實例的時候,會執行訪問檢查。
當反射對象的accessible標志設為true時,則表示反射的對象在使用時應該取消Java語言訪問檢查。反之則檢查。由於JDK的安全檢查耗時較多,所以通過setAccessible(true)的方式關閉安全檢查來提升反射速度。
01.import java.lang.reflect.Field; 02.import java.lang.reflect.Method; 03. 04./** 05. * 用Java反射機制來調用private方法 06. * @author WalkingDog 07. * 08. */ 09. 10.public class Reflect { 11. 12. public static void main(String[] args) throws Exception { 13. 14. //直接創建對象 15. Person person = new Person(); 16. 17. Class<?> personType = person.getClass(); 18. 19. //訪問私有方法 20. //getDeclaredMethod可以獲取到所有方法,而getMethod只能獲取public 21. Method method = personType.getDeclaredMethod("say", String.class); 22. 23. //壓制Java對訪問修飾符的檢查 24. method.setAccessible(true); 25. 26. //調用方法;person為所在對象 27. method.invoke(person, "Hello World !"); 28. 29. //訪問私有屬性 30. Field field = personType.getDeclaredField("name"); 31. 32. field.setAccessible(true); 33. 34. //為屬性設置值;person為所在對象 35. field.set(person, "WalkingDog"); 36. 37. System.out.println("The Value Of The Field is : " + person.getName()); 38. 39. } 40.} 41. 42.//JavaBean 43.class Person{ 44. private String name; 45. 46. //每個JavaBean都應該實現無參構造方法 47. public Person() {} 48. 49. public String getName() { 50. return name; 51. } 52. 53. private void say(String message){ 54. System.out.println("You want to say : " + message); 55. } 56.}打印結果:
You want to say : Hello World !
The Value Of The Field is : WalkingDog