反射认识_03_改变成员变量Fields

时间:2022-04-17 08:00:31
包01:
package ReflectionChange; public class ReflectionPoint_AB {
String str1="access";
String str2="change";
String str3="reflection"; @Override
public String toString(){
return str1+":"+str2+":"+str3;
}
}

  

包02:
package ReflectionChange; import java.lang.reflect.Field; public class Change_AB { public static void main(String[] args) throws Exception {
ReflectionPoint_AB rp=new ReflectionPoint_AB();
ChangeStr(rp);
System.out.println(rp);
} public static void ChangeStr(Object obj) throws Exception{
Field[] fields=obj.getClass().getFields();//通过对象,获得对象的类,通过类获得成员变量
for (Field field : fields) {
if(field.getType()==String.class){
String oldStr = (String)field.get(obj);//获得属于某个对象的变量
System.out.println(oldStr);
String newStr = oldStr.replace('a', 'b');//修改变量:作a换成b的修改
System.out.println(newStr);
field.set(obj, newStr);
}
}
}
}