天天看點

java反射---擷取類的成員變量



package cn.thcic;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

public class Test108 {

 private int age;

 public String addr;

 public static void main(String[] args) {

  Class classInfomation = Test108.class;

  Field[] fieldArr = classInfomation.getFields();

  System.out.println("所有public成員變量:" + fieldArr.length);

  Field[] fieldArrSec = classInfomation.getDeclaredFields();// 傳回所有域,但不包括繼承的域

  System.out.println("所有成員變量:" + fieldArrSec.length);

  try {

   // 得到某一公共域

   Field field = classInfomation.getField("addr");

   Test108 test = (Test108) classInfomation.newInstance();

   test.addr = "zzw";

   // field.get(obj),傳回指定對象上此 Field 表示的字段的值。

   System.out.println(field.get(test));

  } catch (Exception e) {

   e.printStackTrace();

  }

  // 得到所有域中(包括私有域)的某個域

  try {

   Field privateField = classInfomation.getDeclaredField("age");

   Constructor<Test108> con = classInfomation.getConstructor();

   Test108 testSec = (Test108) con.newInstance();

   testSec.age = 10;

   System.out.println(privateField.get(testSec));

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}