本帖最后由 也许依然 于 2014-4-7 17:17 编辑
为什么打印出来的字符没有改变呢?
- public class ReflectPoint {
- private int x;
- public int y;
- String str1 = "ball";
- String str2 = "basketball";
- String str3 = "itcast";
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- public String toString(){
- return str1+":"+str2+":"+str3;
- }
- }
复制代码 ReflectPoint pt1 = new ReflectPoint(3,5);
changeStringValue(pt1);
System.out.println(pt1);
- public static void changeStringValue(Object obj) throws Exception{
- Field [] fields = obj.getClass().getFields();
- for(Field field : fields){
- //判断字段的类型是不是String的类型
- if(field.getType() == String.class){
- String oldValue = (String)field.get(obj);
- String newValue = oldValue.replace('b', 'a');
- //替换完成后要将字段值重新设置
- field.set(obj,newValue);
- }
- }
- }
复制代码
结果为
ball:basketball:itcast
|
|