1. 程式人生 > >Java反射《三》獲取屬性

Java反射《三》獲取屬性

blog tac access field 訪問修飾符 static for student pan

 1 package com.study.reflect;
 2 
 3 import java.lang.reflect.Field;
 4 /**
 5  * 反射,獲取屬性
 6  * @ClassName: FieldDemo 
 7  * @author BlueLake
 8  * @date 2015年9月10日 下午4:21:29
 9  */
10 public class FieldDemo {
11 
12     public static void main(String[] args) throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
13 // 14 Class c = Student.class; 15 //Field,獲取屬性,返回數組 16 Field[] f0 = c.getFields(); 17 for(Field f:f0){ 18 System.out.println(f.getName()+"---"+f.getType());//addr---class java.lang.String 19 } 20 21 //獲得所有的屬性,無論訪問修飾權限。 22 Field[] f1 = c.getDeclaredFields();
23 for(Field f:f1){ 24 System.out.println(f); 25 /* 26 * private java.lang.String com.study.reflect.Student.name 27 private int com.study.reflect.Student.age 28 */ 29 } 30 // 31 Field f2 = c.getDeclaredField("age");
32 Class cla = f2.getType(); 33 String name = f2.getName(); 34 System.out.println(cla+"..."+name);//int...age 35 // 36 Field f3 = c.getDeclaredField("name"); 37 //創建對象 38 Object obj = c.newInstance(); 39 //設置訪問修飾符 40 f2.setAccessible(true); 41 f3.setAccessible(true); 42 //設置屬性值 43 f2.set(obj, 28); 44 f3.set(obj, "明珠"); 45 System.out.println(obj); 46 //獲取屬性 47 System.out.println(f2.get(obj)); 48 System.out.println(f3.get(obj)); 49 } 50 51 }

Java反射《三》獲取屬性