getDeclaredField("x");与set方法的用法

设置
A a = new A();
Field field = a.getClass().getDeclaredField("x");
field.setAccessible(true);
field.set(a, 1);
读取
Field f = a.getClass().getDeclaredField("x");
f.setAccessible(true);
System.out.println(f.get(a));
 
 
举例:

import java.lang.reflect.Field;

public class A {
 private String x = "0";

 public static void main(String[] ag) {
  A a = new A();
  Field field = null;
  try
  {
   field = a.getClass().getDeclaredField("x");
   try
   {
    System.out.println("xiugaiqiandezhi-----------------"
      + field.get(a));
   }
   catch (IllegalArgumentException e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   catch (IllegalAccessException e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  catch (SecurityException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (NoSuchFieldException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  field.setAccessible(true);
  try
  {
   field.set((Object) a, "1");
  }
  catch (IllegalArgumentException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (IllegalAccessException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // 读取
  Field f = null;
  try
  {
   f = a.getClass().getDeclaredField("x");
  }
  catch (SecurityException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (NoSuchFieldException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  f.setAccessible(true);
  try
  {
   System.out.println("xiugaihoudezhi-----------------" + f.get(a));
  }
  catch (IllegalArgumentException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (IllegalAccessException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

输出
xiugaiqiandezhi-----------------0
xiugaihoudezhi-----------------1

你可能感兴趣的:(getDeclaredField("x");与set方法的用法)