1. package com.test;  
  2.  
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5.  
  6. public class ReflectDemo {  
  7.  
  8.     public static void main(String[] args) throws Exception {  
  9.  
  10.         PrivateTest t = new PrivateTest();  
  11.         Field field = Class.forName("com.test.PrivateTest").getDeclaredField(  
  12.                 "str");  
  13.         // 不让Java语言检查访问修饰符  
  14.         field.setAccessible(true);  
  15.         field.set(t, "world");  
  16.         t.getStr();  
  17.  
  18.         Method method2 = Class.forName("com.test.PrivateTest")  
  19.                 .getDeclaredMethod("method", new Class[] {});  
  20.         method2.setAccessible(true);  
  21.         method2.invoke(t, new Object[] {});  
  22.  
  23.     }  
  24. }  
  25.  
  26. class PrivateTest {  
  27.     private String str = "hello";  
  28.  
  29.     public void getStr() {  
  30.         System.out 
  31.                 .println("I'm str,I'm a private field,my old value is hello,now I am --->" 
  32.                         + str);  
  33.     }  
  34.  
  35.     private void method() {  
  36.         System.out.println("I'm in a private method!");  
  37.     }  
  38. }  
  39.  

--------------结果---------------------
I'm str,I'm a private field,my old value is hello,now I am --->world
I'm in a private method!