反射知識2-訪問成員變量

使用到的方法清單
getDeclaredFields():獲得成員變量,返回Field[]
getName():獲得成員變量的名字
getType():獲得成員變量的類型
get(Object obj):返回指定對象上此 Field 表示的字段的值
setInt(Object obj, int i):將字段的值設置爲指定對象上的一個 int 值。

Example_02 Code

public class Example_02 {
int c;
public float f;
protected boolean b;
private String s;
}


Main_02 Code

import java.lang.reflect.Field;

public class Main_02 {
public static void main(String[] args) {
Example_02 example = new Example_02();
Class exampleC = example.getClass();
//獲得所有成員變量
Field[] declaredFields = exampleC.getDeclaredFields();
for(int i = 0; i < declaredFields.length; i++) {
//遍歷所有成員變量
Field field = declaredFields[i];
//獲取成員變量的名字
System.out.println("名稱爲:" + field.getName());
//獲取成員變量類型
Class fieldType = field.getType();
System.out.println("類型爲:" + fieldType);
boolean isTrun = true;
while(isTrun) {
//如果成員變量的修飾符是private,則拋出異常
try {
isTrun = false;
System.out.println("修改前的值爲:" + field.get(example));//返回指定類的指定字段的值
//判斷成員變量的類型是不是Int
if(fieldType.equals(int.class)) {
System.out.println("利用setInt()方法改變成員變量的值");
field.setInt(example, 16);//前者是指定類,後面是要改的數
} else if(fieldType.equals(float.class)) {
System.out.println("利用setFloat()方法改變成員變量的值");
field.setFloat(example, 99.9F);//前者是指定類,後面是要改的數
} else if(fieldType.equals(boolean.class)) {
System.out.println("利用setBoolean()方法改變成員變量的值");
field.setBoolean(example, true);//前者是指定類,後面是要改的數
} else {
System.out.println("利用set()方法改變成員變量的值");
field.set(example, "WWQ");//前者是指定類,後面是要改的數
}
System.out.println("修改後的值爲:" + field.get(example));
} catch (Exception e) {
System.out.println("在設置成員變量的值是拋出異常");
}
}
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章