反射知识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("在设置成员变量的值是抛出异常");
}
}
}
}
}

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