本帖最后由 惠晖 于 2012-12-24 19:31 编辑
public class ReflectTest {
private int x;
private int y;
String str1 = "ball";
String str2 = "basketball";
String str3 = "kajf";
ReflectTest(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return str1 + str2 + str3;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectHello {
/**
* @param argsd
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
ReflectTest p1 = new ReflectTest(2, 3);
changeStringValue(p1);
System.out.println(p1);
}
public static void changeStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
Field[] fields = obj.getClass().getFields();
for (int x = 0; x< fields.length;x++) {
if (fields[x].getType() == String.class) {
String oldValue = (String) fields[x].get(obj);
String newValue = oldValue.replace('b', 'a');
fields[x].set(obj, newValue);
}
}
}
}
为什么 打印出来还是原来的字符串 没有把b换成a |