将一个对象的中的所有String类型的成员变量所对应的字符串内容中的"b"改为"a"。
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;
}
public String toString(){
return str1+" "+str2+" "+str3;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectTest {
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
ReflectPoint pt1 = new ReflectPoint(3,5);
changStringValue(pt1);
System.out.println(pt1);
}
private static void changStringValue(Object obj) throws
IllegalArgumentException,
IllegalAccessException{
Field[] fields=obj.getClass().getFields();
for(Field field:fields){
if(field.getType()==String.class){
//此处用==号更好,因为String 类只有一份字节码,应该是完全相同的
String oldValue=(String)field.get(obj);
String newValue=oldValue.replace("b","a");
field.set(obj, newValue);
}
}
}
}