public class ReflectPoint {
private int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String str3="itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + ", x=" + x + ", y=" + y + "]";
}
}
-------------------------------------------------
public static void changStringValue(Object object) throws IllegalArgumentException, IllegalAccessException{
Field[] fields=object.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType()==String.class){
String oldStr=(String)field.get(object);
String newValue=oldStr.replace('b', 'm');
field.set(object,newValue);//注意要重新set下,第一个参数是对象,第二个参数是新的值
}
}
}
main函数中的内容如下:
ReflectPoint reflectPoint=new ReflectPoint(3,5);
changStringValue(reflectPoint);
System.out.println(reflectPoint);